Skip to content

Commit 2d05a60

Browse files
authored
Add back IComparable-based optimization to FrozenDictionary/Set (#84301)
* Add back IComparable-based optimization to FrozenDictionary/Set We previously had an optimization in FrozenDictionary/Set that special-cased a small number of value types when the default comparer is used... if that type was IComparable, we would sort the types, which would then a) enable us to immediately reject items larger than the known max, and b) enable us to stop searching once we hit an item larger than the one for which we were searching (which then implicitly also immediately rules out items smaller than the known min). We removed that optimization in general because some prominent IComparable implementations don't always work, in particular container types like ValueTuple that implement IComparable but then it's only functional if the contained types are also comparable. This commit puts it back for an allow-list of types. * Address PR feedback
1 parent 18e2c5f commit 2d05a60

File tree

6 files changed

+222
-1
lines changed

6 files changed

+222
-1
lines changed

src/libraries/System.Collections.Immutable/src/System.Collections.Immutable.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ The System.Collections.Immutable library is built-in as part of the shared frame
2929
<Compile Include="System\Collections\Frozen\KeysAndValuesFrozenDictionary.cs" />
3030
<Compile Include="System\Collections\Frozen\SmallFrozenDictionary.cs" />
3131
<Compile Include="System\Collections\Frozen\SmallFrozenSet.cs" />
32+
<Compile Include="System\Collections\Frozen\SmallValueTypeComparableFrozenDictionary.cs" />
33+
<Compile Include="System\Collections\Frozen\SmallValueTypeComparableFrozenSet.cs" />
3234
<Compile Include="System\Collections\Frozen\SmallValueTypeDefaultComparerFrozenDictionary.cs" />
3335
<Compile Include="System\Collections\Frozen\SmallValueTypeDefaultComparerFrozenSet.cs" />
3436
<Compile Include="System\Collections\Frozen\ValueTypeDefaultComparerFrozenDictionary.cs" />

src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/Constants.cs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
using System.Text;
5+
46
namespace System.Collections.Frozen
57
{
68
/// <summary>
@@ -28,5 +30,53 @@ internal static class Constants
2830
/// hashing ValueTypeDefaultComparerFrozenDictionary/Set.
2931
/// </remarks>
3032
public const int MaxItemsInSmallValueTypeFrozenCollection = 10;
33+
34+
/// <summary>
35+
/// Whether the <typeparamref name="T"/> is known to implement <see cref="IComparable{T}"/> safely and efficiently,
36+
/// such that its comparison operations should be used in searching for types in small collections.
37+
/// </summary>
38+
/// <remarks>
39+
/// This does not automatically return true for any type that implements <see cref="IComparable{T}"/>.
40+
/// Doing so leads to problems for container types (e.g. ValueTuple{T1, T2}) where the
41+
/// container implements <see cref="IComparable{T}"/> to delegate to its contained items' implementation
42+
/// but those then don't provide such support.
43+
/// </remarks>
44+
public static bool IsKnownComparable<T>() =>
45+
// This list covers all of the IComparable<T> value types in Corelib that aren't containers (like ValueTuple).
46+
typeof(T) == typeof(bool) ||
47+
typeof(T) == typeof(sbyte) ||
48+
typeof(T) == typeof(byte) ||
49+
typeof(T) == typeof(char) ||
50+
typeof(T) == typeof(short) ||
51+
typeof(T) == typeof(ushort) ||
52+
typeof(T) == typeof(int) ||
53+
typeof(T) == typeof(uint) ||
54+
typeof(T) == typeof(long) ||
55+
typeof(T) == typeof(ulong) ||
56+
typeof(T) == typeof(nint) ||
57+
typeof(T) == typeof(nuint) ||
58+
typeof(T) == typeof(decimal) ||
59+
typeof(T) == typeof(float) ||
60+
typeof(T) == typeof(double) ||
61+
typeof(T) == typeof(decimal) ||
62+
typeof(T) == typeof(TimeSpan) ||
63+
typeof(T) == typeof(DateTime) ||
64+
typeof(T) == typeof(DateTimeOffset) ||
65+
typeof(T) == typeof(Guid) ||
66+
#if NETCOREAPP3_0_OR_GREATER
67+
typeof(T) == typeof(Rune) ||
68+
#endif
69+
#if NET5_0_OR_GREATER
70+
typeof(T) == typeof(Half) ||
71+
#endif
72+
#if NET6_0_OR_GREATER
73+
typeof(T) == typeof(DateOnly) ||
74+
typeof(T) == typeof(TimeOnly) ||
75+
#endif
76+
#if NET7_0_OR_GREATER
77+
typeof(T) == typeof(Int128) ||
78+
typeof(T) == typeof(UInt128) ||
79+
#endif
80+
typeof(T).IsEnum;
3181
}
3282
}

src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenDictionary.cs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
using System.Diagnostics;
77
using System.Diagnostics.CodeAnalysis;
88
using System.Linq;
9-
using System.Numerics;
109
using System.Runtime.CompilerServices;
1110

1211
namespace System.Collections.Frozen
@@ -202,14 +201,26 @@ private static FrozenDictionary<TKey, TValue> ChooseImplementationOptimizedForRe
202201
{
203202
if (source.Count <= Constants.MaxItemsInSmallValueTypeFrozenCollection)
204203
{
204+
// If the key is a something we know we can efficiently compare, use a specialized implementation
205+
// that will enable quickly ruling out values outside of the range of keys stored.
206+
if (Constants.IsKnownComparable<TKey>())
207+
{
208+
return (FrozenDictionary<TKey, TValue>)(object)new SmallValueTypeComparableFrozenDictionary<TKey, TValue>(source);
209+
}
210+
211+
// Otherwise, use an implementation optimized for a small number of value types using the default comparer.
205212
return (FrozenDictionary<TKey, TValue>)(object)new SmallValueTypeDefaultComparerFrozenDictionary<TKey, TValue>(source);
206213
}
207214

215+
// Use a hash-based implementation.
216+
217+
// For Int32 keys, we can reuse the key storage as the hash storage, saving on space and extra indirection.
208218
if (typeof(TKey) == typeof(int))
209219
{
210220
return (FrozenDictionary<TKey, TValue>)(object)new Int32FrozenDictionary<TValue>((Dictionary<int, TValue>)(object)source);
211221
}
212222

223+
// Fallback to an implementation usable with any value type and the default comparer.
213224
return new ValueTypeDefaultComparerFrozenDictionary<TKey, TValue>(source);
214225
}
215226
}

src/libraries/System.Collections.Immutable/src/System/Collections/Frozen/FrozenSet.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,14 +133,26 @@ private static FrozenSet<T> ChooseImplementationOptimizedForReading<T>(HashSet<T
133133
{
134134
if (source.Count <= Constants.MaxItemsInSmallValueTypeFrozenCollection)
135135
{
136+
// If the type is a something we know we can efficiently compare, use a specialized implementation
137+
// that will enable quickly ruling out values outside of the range of keys stored.
138+
if (Constants.IsKnownComparable<T>())
139+
{
140+
return (FrozenSet<T>)(object)new SmallValueTypeComparableFrozenSet<T>(source);
141+
}
142+
143+
// Otherwise, use an implementation optimized for a small number of value types using the default comparer.
136144
return (FrozenSet<T>)(object)new SmallValueTypeDefaultComparerFrozenSet<T>(source);
137145
}
138146

147+
// Use a hash-based implementation.
148+
149+
// For Int32 values, we can reuse the item storage as the hash storage, saving on space and extra indirection.
139150
if (typeof(T) == typeof(int))
140151
{
141152
return (FrozenSet<T>)(object)new Int32FrozenSet((HashSet<int>)(object)source);
142153
}
143154

155+
// Fallback to an implementation usable with any value type and the default comparer.
144156
return new ValueTypeDefaultComparerFrozenSet<T>(source);
145157
}
146158
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Collections.Generic;
5+
using System.Diagnostics;
6+
using System.Linq;
7+
using System.Runtime.CompilerServices;
8+
9+
namespace System.Collections.Frozen
10+
{
11+
/// <summary>Provides a frozen dictionary to use when the key is a value type, the default comparer is used, and the item count is small.</summary>
12+
/// <remarks>
13+
/// While not constrained in this manner, the <typeparamref name="TKey"/> must be an <see cref="IComparable{T}"/>.
14+
/// This implementation is only used for a set of types that have a known-good <see cref="IComparable{T}"/> implementation; it's not
15+
/// used for an <see cref="IComparable{T}"/> as we can't know for sure whether it's valid, e.g. if the TKey is a ValueTuple`2, it itself
16+
/// is comparable, but its items might not be such that trying to compare it will result in exception.
17+
/// </remarks>
18+
internal sealed class SmallValueTypeComparableFrozenDictionary<TKey, TValue> : FrozenDictionary<TKey, TValue>
19+
where TKey : notnull
20+
{
21+
private readonly TKey[] _keys;
22+
private readonly TValue[] _values;
23+
private readonly TKey _max;
24+
25+
internal SmallValueTypeComparableFrozenDictionary(Dictionary<TKey, TValue> source) : base(EqualityComparer<TKey>.Default)
26+
{
27+
Debug.Assert(default(TKey) is IComparable<TKey>);
28+
Debug.Assert(default(TKey) is not null);
29+
Debug.Assert(typeof(TKey).IsValueType);
30+
31+
Debug.Assert(source.Count != 0);
32+
Debug.Assert(ReferenceEquals(source.Comparer, EqualityComparer<TKey>.Default));
33+
34+
_keys = source.Keys.ToArray();
35+
_values = source.Values.ToArray();
36+
37+
Array.Sort(_keys, _values);
38+
_max = _keys[_keys.Length - 1];
39+
}
40+
41+
private protected override TKey[] KeysCore => _keys;
42+
private protected override TValue[] ValuesCore => _values;
43+
private protected override Enumerator GetEnumeratorCore() => new Enumerator(_keys, _values);
44+
private protected override int CountCore => _keys.Length;
45+
46+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
47+
private protected override ref readonly TValue GetValueRefOrNullRefCore(TKey key)
48+
{
49+
if (Comparer<TKey>.Default.Compare(key, _max) <= 0)
50+
{
51+
TKey[] keys = _keys;
52+
for (int i = 0; i < keys.Length; i++)
53+
{
54+
int c = Comparer<TKey>.Default.Compare(key, keys[i]);
55+
if (c <= 0)
56+
{
57+
if (c == 0)
58+
{
59+
return ref _values[i];
60+
}
61+
62+
break;
63+
}
64+
}
65+
}
66+
67+
return ref Unsafe.NullRef<TValue>();
68+
}
69+
}
70+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Collections.Generic;
5+
using System.Collections.Immutable;
6+
using System.Diagnostics;
7+
using System.Linq;
8+
9+
namespace System.Collections.Frozen
10+
{
11+
/// <summary>Provides a frozen set to use when the item is a value type, the default comparer is used, and the item count is small.</summary>
12+
/// <remarks>
13+
/// While not constrained in this manner, the <typeparamref name="T"/> must be an <see cref="IComparable{T}"/>.
14+
/// This implementation is only used for a set of types that have a known-good <see cref="IComparable{T}"/> implementation; it's not
15+
/// used for an <see cref="IComparable{T}"/> as we can't know for sure whether it's valid, e.g. if the T is a ValueTuple`2, it itself
16+
/// is comparable, but its items might not be such that trying to compare it will result in exception.
17+
/// </remarks>
18+
internal sealed class SmallValueTypeComparableFrozenSet<T> : FrozenSetInternalBase<T, SmallValueTypeComparableFrozenSet<T>.GSW>
19+
{
20+
private readonly T[] _items;
21+
private readonly T _max;
22+
23+
internal SmallValueTypeComparableFrozenSet(HashSet<T> source) : base(EqualityComparer<T>.Default)
24+
{
25+
Debug.Assert(default(T) is IComparable<T>);
26+
Debug.Assert(default(T) is not null);
27+
Debug.Assert(typeof(T).IsValueType);
28+
29+
Debug.Assert(source.Count != 0);
30+
Debug.Assert(ReferenceEquals(source.Comparer, EqualityComparer<T>.Default));
31+
32+
_items = source.ToArray();
33+
34+
Array.Sort(_items);
35+
_max = _items[_items.Length - 1];
36+
}
37+
38+
private protected override T[] ItemsCore => _items;
39+
private protected override Enumerator GetEnumeratorCore() => new Enumerator(_items);
40+
private protected override int CountCore => _items.Length;
41+
42+
private protected override int FindItemIndex(T item)
43+
{
44+
if (Comparer<T>.Default.Compare(item, _max) <= 0)
45+
{
46+
T[] items = _items;
47+
for (int i = 0; i < items.Length; i++)
48+
{
49+
int c = Comparer<T>.Default.Compare(item, items[i]);
50+
if (c <= 0)
51+
{
52+
if (c == 0)
53+
{
54+
return i;
55+
}
56+
57+
break;
58+
}
59+
}
60+
}
61+
62+
return -1;
63+
}
64+
65+
internal struct GSW : IGenericSpecializedWrapper
66+
{
67+
private SmallValueTypeComparableFrozenSet<T> _set;
68+
public void Store(FrozenSet<T> set) => _set = (SmallValueTypeComparableFrozenSet<T>)set;
69+
70+
public int Count => _set.Count;
71+
public IEqualityComparer<T> Comparer => _set.Comparer;
72+
public int FindItemIndex(T item) => _set.FindItemIndex(item);
73+
public Enumerator GetEnumerator() => _set.GetEnumerator();
74+
}
75+
}
76+
}

0 commit comments

Comments
 (0)