Skip to content

Commit be7f83e

Browse files
authored
Optimize dictionary access with CollectionsMarshal.GetValueRefOrAddDefault within Trie and Lookup (#195)
1 parent 3566826 commit be7f83e

File tree

2 files changed

+9
-9
lines changed

2 files changed

+9
-9
lines changed

Akade.IndexedSet/DataStructures/Lookup.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
namespace Akade.IndexedSet.DataStructures;
1+
using System.Runtime.InteropServices;
2+
3+
namespace Akade.IndexedSet.DataStructures;
24

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

1214
public bool Add(TKey key, TValue value)
1315
{
14-
if (!_values.TryGetValue(key, out HashSet<TValue>? keySet))
15-
{
16-
keySet = _values[key] = [];
17-
}
16+
ref HashSet<TValue>? keySet = ref CollectionsMarshal.GetValueRefOrAddDefault(_values, key, out _);
17+
keySet ??= [];
1818

1919
if (keySet.Add(value))
2020
{

Akade.IndexedSet/DataStructures/Trie.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Akade.IndexedSet.Extensions;
22
using Akade.IndexedSet.Utils;
33
using System.Diagnostics.CodeAnalysis;
4+
using System.Runtime.InteropServices;
45

56
namespace Akade.IndexedSet.DataStructures;
67

@@ -177,11 +178,10 @@ internal bool Add(ReadOnlySpan<char> key, TElement element)
177178
else
178179
{
179180
_children ??= [];
180-
if (!_children.TryGetValue(key[0], out TrieNode? trieNode))
181-
{
182-
_children[key[0]] = trieNode = new();
183-
}
184181

182+
ref TrieNode? trieNode = ref CollectionsMarshal.GetValueRefOrAddDefault(_children, key[0], out _);
183+
184+
trieNode ??= new();
185185
return trieNode.Add(key[1..], element);
186186
}
187187
}

0 commit comments

Comments
 (0)