Skip to content

Improve LRU performance in C# #481

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions bench/algorithm/lru/2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,21 @@ public static void Main(string[] args)
}
}

public class Pair<TK, TV>
{
public struct Pair<TK, TV>
{
public TK Key;

public TV Value;
public TV Value;
}

public class LRU<TK, TV>
where TK : notnull
where TV : notnull
{
public int Size { get; private set; }

private readonly Dictionary<TK, LinkedListNode<Pair<TK, TV>>> _key_lookup;

private readonly LinkedList<Pair<TK, TV>> _entries;

public LRU(int size)
public LRU(int size)
{
Size = size;
_key_lookup = new Dictionary<TK, LinkedListNode<Pair<TK, TV>>>(size);
Expand All @@ -58,7 +57,11 @@ public bool TryGet(TK key, out TV value)
{
if (_key_lookup.TryGetValue(key, out var node))
{
#if NET5_0_OR_GREATER
value = node.ValueRef.Value;
#else
value = node.Value.Value;
#endif
_entries.Remove(node);
_entries.AddLast(node);
return true;
Expand All @@ -71,17 +74,17 @@ public void Put(TK key, TV value)
{
if (_key_lookup.TryGetValue(key, out var node))
{
node.Value.Value = value;
node.ValueRef.Value = value;
_entries.Remove(node);
_entries.AddLast(node);
}
else if (_entries.Count == Size)
{
var first = _entries.First;
_key_lookup.Remove(first.Value.Key);
_key_lookup.Remove(first!.Value.Key);
_entries.RemoveFirst();
first.Value.Key = key;
first.Value.Value = value;
first.ValueRef.Key = key;
first.ValueRef.Value = value;
_entries.AddLast(first);
_key_lookup[key] = first;
}
Expand Down
Loading