Skip to content
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

Optimize dictionary access with CollectionsMarshal.GetValueRefOrAddDe… #195

Merged
merged 1 commit into from
Jan 19, 2025
Merged
Show file tree
Hide file tree
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
10 changes: 5 additions & 5 deletions Akade.IndexedSet/DataStructures/Lookup.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace Akade.IndexedSet.DataStructures;
using System.Runtime.InteropServices;

namespace Akade.IndexedSet.DataStructures;

/// <summary>
/// Modifiable lookup based on <see cref="Dictionary{TKey, TValue}"/> with <see cref="HashSet{T}"/> as value collection per key.
Expand All @@ -11,10 +13,8 @@ internal class Lookup<TKey, TValue>

public bool Add(TKey key, TValue value)
{
if (!_values.TryGetValue(key, out HashSet<TValue>? keySet))
{
keySet = _values[key] = [];
}
ref HashSet<TValue>? keySet = ref CollectionsMarshal.GetValueRefOrAddDefault(_values, key, out _);
keySet ??= [];

if (keySet.Add(value))
{
Expand Down
8 changes: 4 additions & 4 deletions Akade.IndexedSet/DataStructures/Trie.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Akade.IndexedSet.Extensions;
using Akade.IndexedSet.Utils;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;

namespace Akade.IndexedSet.DataStructures;

Expand Down Expand Up @@ -177,11 +178,10 @@ internal bool Add(ReadOnlySpan<char> key, TElement element)
else
{
_children ??= [];
if (!_children.TryGetValue(key[0], out TrieNode? trieNode))
{
_children[key[0]] = trieNode = new();
}

ref TrieNode? trieNode = ref CollectionsMarshal.GetValueRefOrAddDefault(_children, key[0], out _);

trieNode ??= new();
return trieNode.Add(key[1..], element);
}
}
Expand Down
Loading