From 2e349d77b7263638fb9ea148499e5c9747072fcd Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Tue, 2 Dec 2025 17:18:57 -0800 Subject: [PATCH 1/2] Reduce unsafe usage in AdaptiveCapacityDictionary --- src/Shared/Dictionary/AdaptiveCapacityDictionary.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs b/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs index 9460751251b8..f30d3cb0a8af 100644 --- a/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs +++ b/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs @@ -7,7 +7,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Internal; @@ -545,8 +544,7 @@ private Span> ArrayStorageSpan Debug.Assert(_arrayStorage is not null); Debug.Assert(_count <= _arrayStorage.Length); - ref var r = ref MemoryMarshal.GetArrayDataReference(_arrayStorage); - return MemoryMarshal.CreateSpan(ref r, _count); + return _arrayStorage.AsSpan(0, _count); } } @@ -558,9 +556,10 @@ private int FindIndex(TKey key) if (_count > 0) { - for (var i = 0; i < ArrayStorageSpan.Length; ++i) + var arrayStorageSpanLocal = ArrayStorageSpan; // call Span.Slice once rather than within loop + for (var i = 0; i < arrayStorageSpanLocal.Length; ++i) { - if (_comparer.Equals(ArrayStorageSpan[i].Key, key)) + if (_comparer.Equals(arrayStorageSpanLocal[i].Key, key)) { return i; } From 5deaf05051b69ccd88e083b23eb5eefb0ac97b40 Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Tue, 2 Dec 2025 17:41:54 -0800 Subject: [PATCH 2/2] Clarify local var name + comments --- src/Shared/Dictionary/AdaptiveCapacityDictionary.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs b/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs index f30d3cb0a8af..d777e164a62b 100644 --- a/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs +++ b/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs @@ -556,10 +556,10 @@ private int FindIndex(TKey key) if (_count > 0) { - var arrayStorageSpanLocal = ArrayStorageSpan; // call Span.Slice once rather than within loop - for (var i = 0; i < arrayStorageSpanLocal.Length; ++i) + var localSpan = ArrayStorageSpan; // incur slice + bounds check once upfront instead of within loop + for (var i = 0; i < localSpan.Length; ++i) { - if (_comparer.Equals(arrayStorageSpanLocal[i].Key, key)) + if (_comparer.Equals(localSpan[i].Key, key)) { return i; }