-
Notifications
You must be signed in to change notification settings - Fork 41
Add alternate key support to ConcurrentLru #739
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
Merged
bitfaster
merged 22 commits into
main
from
copilot/add-alternate-cache-from-concurrentlru
Mar 29, 2026
+548
−52
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
554fe2f
Implement alternate cache API
Copilot e088f6f
Document alternate cache API
Copilot 776481e
Refine alternate cache get-or-add
Copilot fa5b42c
Extract alternate cache interface to top-level namespace
Copilot 51324ab
Use ReadOnlySpan alternate keys in positive tests
Copilot b303547
Rename alternate cache API to alternate lookup
Copilot 75d5105
Cache alternate lookup adapter in ConcurrentLru
Copilot b9ea646
Extract alternate lookup collection helpers
Copilot b3577b4
Remove redundant alternate lookup check
Copilot 3e40ba9
Add alternate lookup TryAdd and AddOrUpdate
Copilot 22a0dd0
Merge branch 'main' into copilot/add-alternate-cache-from-concurrentlru
bitfaster 64275ae
Rename alternate lookup AddOrUpdate to TryUpdate
Copilot 2075160
Extract shared ConcurrentLru TryUpdate logic
Copilot 5420437
Remove alternate lookup TryAdd API
Copilot 7d8fa3e
Add alternate lookup AddOrUpdate
Copilot 023c085
Cache alternate key in AddOrUpdate
Copilot eb9eff4
bench
07526ab
Merge branch 'copilot/add-alternate-cache-from-concurrentlru' of http…
4df0b11
Add alternate lookup soak tests
Copilot 22314e5
Clarify alternate soak lambda names
Copilot eb825a4
Use TArg in alternate soak test
Copilot 07c3fee
Add alternate lookup remove soak test
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
BitFaster.Caching.Benchmarks/Lru/LruJustGetOrAddAlternate.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using Benchly; | ||
| using BenchmarkDotNet.Attributes; | ||
| using BenchmarkDotNet.Diagnosers; | ||
| using BitFaster.Caching.Lru; | ||
|
|
||
| namespace BitFaster.Caching.Benchmarks | ||
| { | ||
| // Note: to run in VS, make .net9 the first target fmk in the .vcproj | ||
| #if Windows | ||
| [DisassemblyDiagnoser(printSource: true, maxDepth: 5)] | ||
| #endif | ||
| [MemoryDiagnoser(displayGenColumns: false)] | ||
| [HideColumns("Job", "Median", "RatioSD", "Alloc Ratio")] | ||
| [ColumnChart(Title = "Lookup Latency ({JOB})", Output = OutputMode.PerJob, Colors = "darkslategray,royalblue,royalblue,royalblue,royalblue,royalblue,royalblue,royalblue,#ffbf00,limegreen,indianred,indianred")] | ||
| public class LruJustGetOrAddAlternate | ||
| { | ||
| private static readonly ConcurrentLru<string, int> concurrentLru = new ConcurrentLru<string, int>(8, 9, EqualityComparer<string>.Default); | ||
|
|
||
| [Benchmark(Baseline = true)] | ||
| public int ConcurrentLru() | ||
| { | ||
| Func<string, int> func = x => 1; | ||
| return concurrentLru.GetOrAdd("foo", func); | ||
| } | ||
|
|
||
| #if NET9_0_OR_GREATER | ||
| private static readonly IAlternateLookup<ReadOnlySpan<char>, string, int> alternate = concurrentLru.GetAlternateLookup<ReadOnlySpan<char>>(); | ||
|
|
||
| [Benchmark()] | ||
| public int ConcurrentLruAlternate() | ||
| { | ||
| Func<ReadOnlySpan<char>, int> func = x => 1; | ||
| return alternate.GetOrAdd("foo".AsSpan(), func); | ||
| } | ||
| #endif | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
115 changes: 115 additions & 0 deletions
115
BitFaster.Caching.UnitTests/Lru/ConcurrentLruAlternateLookupTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| #if NET9_0_OR_GREATER | ||
| using System; | ||
| using BitFaster.Caching.Lru; | ||
| using FluentAssertions; | ||
| using Xunit; | ||
|
|
||
| namespace BitFaster.Caching.UnitTests.Lru | ||
| { | ||
| public class ConcurrentLruAlternateLookupTests | ||
| { | ||
| [Fact] | ||
| public void TryGetAlternateLookupReturnsLookupForCompatibleComparer() | ||
| { | ||
| var cache = new ConcurrentLru<string, string>(1, 3, StringComparer.Ordinal); | ||
| cache.GetOrAdd("42", _ => "value"); | ||
| ReadOnlySpan<char> key = "42"; | ||
|
|
||
| cache.TryGetAlternateLookup<ReadOnlySpan<char>>(out var alternate).Should().BeTrue(); | ||
| alternate.TryGet(key, out var value).Should().BeTrue(); | ||
| value.Should().Be("value"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void GetAlternateLookupThrowsForIncompatibleComparer() | ||
| { | ||
| var cache = new ConcurrentLru<string, string>(1, 3, StringComparer.Ordinal); | ||
|
|
||
| Action act = () => cache.GetAlternateLookup<int>(); | ||
|
|
||
| act.Should().Throw<InvalidOperationException>().WithMessage("Incompatible comparer"); | ||
| cache.TryGetAlternateLookup<int>(out var alternate).Should().BeFalse(); | ||
| alternate.Should().BeNull(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AlternateLookupTryRemoveReturnsActualKeyAndValue() | ||
| { | ||
| var cache = new ConcurrentLru<string, string>(1, 3, StringComparer.Ordinal); | ||
| cache.GetOrAdd("42", _ => "value"); | ||
| var alternate = cache.GetAlternateLookup<ReadOnlySpan<char>>(); | ||
| ReadOnlySpan<char> key = "42"; | ||
|
|
||
| alternate.TryRemove(key, out var actualKey, out var value).Should().BeTrue(); | ||
|
|
||
| actualKey.Should().Be("42"); | ||
| value.Should().Be("value"); | ||
| cache.TryGet("42", out _).Should().BeFalse(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AlternateLookupGetOrAddUsesAlternateKeyOnMissAndHit() | ||
| { | ||
| var cache = new ConcurrentLru<string, string>(1, 3, StringComparer.Ordinal); | ||
| var alternate = cache.GetAlternateLookup<ReadOnlySpan<char>>(); | ||
| var factoryCalls = 0; | ||
| ReadOnlySpan<char> key = "42"; | ||
|
|
||
| alternate.GetOrAdd(key, key => | ||
| { | ||
| factoryCalls++; | ||
| return $"value-{key.ToString()}"; | ||
| }).Should().Be("value-42"); | ||
|
|
||
| alternate.GetOrAdd(key, (_, prefix) => | ||
| { | ||
| factoryCalls++; | ||
| return prefix; | ||
| }, "unused").Should().Be("value-42"); | ||
|
|
||
| factoryCalls.Should().Be(1); | ||
| cache.TryGet("42", out var value).Should().BeTrue(); | ||
| value.Should().Be("value-42"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AlternateLookupTryUpdateReturnsFalseForMissingKeyAndUpdatesExistingValue() | ||
| { | ||
| var cache = new ConcurrentLru<string, string>(1, 3, StringComparer.Ordinal); | ||
| var alternate = cache.GetAlternateLookup<ReadOnlySpan<char>>(); | ||
| ReadOnlySpan<char> key = "42"; | ||
|
|
||
| alternate.TryUpdate(key, "value-42").Should().BeFalse(); | ||
| cache.TryGet("42", out _).Should().BeFalse(); | ||
|
|
||
| cache.GetOrAdd("42", _ => "value-42"); | ||
| alternate.TryUpdate(key, "updated").Should().BeTrue(); | ||
|
|
||
| cache.TryGet("42", out var value).Should().BeTrue(); | ||
| value.Should().Be("updated"); | ||
| alternate.TryGet(key, out value).Should().BeTrue(); | ||
| value.Should().Be("updated"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AlternateLookupAddOrUpdateAddsMissingValueAndUpdatesExistingValue() | ||
| { | ||
| var cache = new ConcurrentLru<string, string>(1, 3, StringComparer.Ordinal); | ||
| var alternate = cache.GetAlternateLookup<ReadOnlySpan<char>>(); | ||
| ReadOnlySpan<char> key = "42"; | ||
|
|
||
| alternate.AddOrUpdate(key, "value-42"); | ||
|
|
||
| cache.TryGet("42", out var value).Should().BeTrue(); | ||
| value.Should().Be("value-42"); | ||
|
|
||
| alternate.AddOrUpdate(key, "updated"); | ||
|
|
||
| cache.TryGet("42", out value).Should().BeTrue(); | ||
| value.Should().Be("updated"); | ||
| alternate.TryGet(key, out value).Should().BeTrue(); | ||
| value.Should().Be("updated"); | ||
| } | ||
| } | ||
| } | ||
| #endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| using System.Collections.Concurrent; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics; | ||
| using System.Runtime.CompilerServices; | ||
|
|
||
| namespace BitFaster.Caching | ||
| { | ||
| internal static class CollectionExtensions | ||
| { | ||
| #if NET9_0_OR_GREATER | ||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| internal static bool IsCompatibleKey<TAlternateKey, TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary) | ||
| where TAlternateKey : notnull, allows ref struct | ||
| where TKey : notnull | ||
| { | ||
| return dictionary.Comparer is IAlternateEqualityComparer<TAlternateKey, TKey>; | ||
| } | ||
|
|
||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| internal static IAlternateEqualityComparer<TAlternateKey, TKey> GetAlternateComparer<TAlternateKey, TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary) | ||
| where TAlternateKey : notnull, allows ref struct | ||
| where TKey : notnull | ||
| { | ||
| Debug.Assert(dictionary.IsCompatibleKey<TAlternateKey, TKey, TValue>()); | ||
| return Unsafe.As<IAlternateEqualityComparer<TAlternateKey, TKey>>(dictionary.Comparer!); | ||
| } | ||
| #endif | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| #if NET9_0_OR_GREATER | ||
| using System; | ||
| using System.Diagnostics.CodeAnalysis; | ||
|
|
||
| namespace BitFaster.Caching | ||
| { | ||
| /// <summary> | ||
| /// Provides an alternate-key lookup over a cache. | ||
| /// </summary> | ||
| /// <typeparam name="TAlternateKey">The alternate key type.</typeparam> | ||
| /// <typeparam name="TKey">The cache key type.</typeparam> | ||
| /// <typeparam name="TValue">The cache value type.</typeparam> | ||
| public interface IAlternateLookup<TAlternateKey, TKey, TValue> | ||
| where TAlternateKey : notnull, allows ref struct | ||
| where TKey : notnull | ||
| { | ||
| /// <summary> | ||
| /// Attempts to get a value using an alternate key. | ||
| /// </summary> | ||
| /// <param name="key">The alternate key.</param> | ||
| /// <param name="value">The cached value when found.</param> | ||
| /// <returns><see langword="true" /> when the key is found; otherwise, <see langword="false" />.</returns> | ||
| bool TryGet(TAlternateKey key, [MaybeNullWhen(false)] out TValue value); | ||
|
|
||
| /// <summary> | ||
| /// Attempts to remove a value using an alternate key. | ||
| /// </summary> | ||
| /// <param name="key">The alternate key.</param> | ||
| /// <param name="actualKey">The removed cache key.</param> | ||
| /// <param name="value">The removed value.</param> | ||
| /// <returns><see langword="true" /> when the key is found; otherwise, <see langword="false" />.</returns> | ||
| bool TryRemove(TAlternateKey key, [MaybeNullWhen(false)] out TKey actualKey, [MaybeNullWhen(false)] out TValue value); | ||
|
|
||
| /// <summary> | ||
| /// Attempts to update an existing value using an alternate key. | ||
| /// </summary> | ||
| /// <param name="key">The alternate key.</param> | ||
| /// <param name="value">The value to update.</param> | ||
| /// <returns><see langword="true" /> when the key was updated; otherwise, <see langword="false" />.</returns> | ||
| bool TryUpdate(TAlternateKey key, TValue value); | ||
|
|
||
| /// <summary> | ||
| /// Adds a value using an alternate key or updates the existing value. | ||
| /// </summary> | ||
| /// <param name="key">The alternate key.</param> | ||
| /// <param name="value">The value to add or update.</param> | ||
| void AddOrUpdate(TAlternateKey key, TValue value); | ||
|
|
||
| /// <summary> | ||
| /// Gets an existing value or adds a new value using an alternate key. | ||
| /// </summary> | ||
| /// <param name="key">The alternate key.</param> | ||
| /// <param name="valueFactory">The value factory.</param> | ||
| /// <returns>The cached value.</returns> | ||
| TValue GetOrAdd(TAlternateKey key, Func<TAlternateKey, TValue> valueFactory); | ||
|
|
||
| /// <summary> | ||
| /// Gets an existing value or adds a new value using an alternate key and factory argument. | ||
| /// </summary> | ||
| /// <typeparam name="TArg">The factory argument type.</typeparam> | ||
| /// <param name="key">The alternate key.</param> | ||
| /// <param name="valueFactory">The value factory.</param> | ||
| /// <param name="factoryArgument">The factory argument.</param> | ||
| /// <returns>The cached value.</returns> | ||
| TValue GetOrAdd<TArg>(TAlternateKey key, Func<TAlternateKey, TArg, TValue> valueFactory, TArg factoryArgument); | ||
| } | ||
bitfaster marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| #endif | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.