Skip to content

Speed up KeyAnalyzer for substring based frozen collections - #89689

Closed
IDisposable wants to merge 7 commits into
dotnet:mainfrom
IDisposable:trait-based
Closed

Speed up KeyAnalyzer for substring based frozen collections#89689
IDisposable wants to merge 7 commits into
dotnet:mainfrom
IDisposable:trait-based

Conversation

@IDisposable

@IDisposableIDisposable commented Jul 30, 2023

Copy link
Copy Markdown
Contributor

Building on PR #88516, I tried making everything as explicitly inline-able and sealed to get the JIT to eliminate any conditional jumps in the hot loop by teasing out the various comparator options into trait-like classes to mix in to get sealed classes where all the logic in conditional-free (down to the internals of the String.AsSpan() methods themselves. This required making some potentially hard-to-read changes, but the essence is that now we construct a comparer and hash set for the from-the-left attempt, and then lazily construct another comparer and matching hash set only if we need one for from-the-right attempt.

Since in the vast number of cases, we're going to spend the bulk of the execution time iterating through the uniqueStrings we're presented with, the overhead of having another comparer/collection is pretty low in comparison.

To ensure we don't bloat memory. I reversed when we clean the set to right before we return false from HasSufficientUniquenessFactor since we know that we're going to get called again for a different index/count... this means that both HashSet<string>s spend their lifetimes empty except when being tested (we could clear them on success, as well, but the old code didn't bother).

The resulting SubstringComparer classes could be useful elsewhere, but are currently just internal to the System.Collections.Immutable assembly. I suspect we could/should pass them out in the AnalysisResults and use the chosen substring extractor as it already has the offset, length, and ignore/honor case encapsulated, but that would be another pass. If we do that, I would like to add some tests for those classes first.

I also added some more tests to the KeyAnalyser tests to verify newly exposed behavior.

The other changes imported from PR #88516 here are:

  • Eliminate the the inner TryUseSubstring because we can just early return the calculated results as we build them
  • Hoist the calculation of acceptableNonUniqueCount out to the top level since it never changes (which means we pass that into the HasSufficientUniquenessFactor method for it to "use up" internally (passed by value, so unchanged at call-site)
  • Eliminated the delegate ReadOnlySpan<char> GetSpan and use, which helps reduce dynamic dispatch overhead in the CreateAnalysisResults method
  • Eliminated the IsLeft field of the SubstringComparer since we can tell by the Index being negative that we're doing right-justified slicing (and documented that on the class)
  • Changed the logic managing the Index and Count on the comparer for right-justified substrings.
  • Added [MethodImpl(MethodImplOptions.AggressiveInlining)] to the Equals and GetHashCode overrides.

The slicing is really only changed once per Count, so move the
IsLeft-dependent logic into `Slicer` method and eliminate the `GetSpan` delegate.
Changed to also pass the already-computed `set` of unique substrings to the `CreateAnalysisResults` method, so we don't recompute the slices twice. In order than either the set or the original `uniqueStrings` can be passed, swapped that argument for the `Analyze` method to take the `uniqueStrings` as a `string[]` (which it already is at all call-sites).
Subtle bug in that the entire string is being placed in the set, not the span.
Since we are working with the same set of input strings in each strategy there's no reason to take the length every time we make an attempt (per count, both left and right justified).
Hoist the calculation of the acceptable number of collisions out to the top, do it once, and pass that number into the `HasSufficientUniquenessFactor` method for it to (locally) use up.
Benchmarks ever so slightly better.
Looks like the overhead of IEnumerable<string> is not worth the savings for the benchmark test data. Perhaps it would matter less if we were freezing more strings, but not likely
@ghostghost added area-System.Collections community-contribution Indicates that the PR has been added by a community member labels Jul 30, 2023
@ghost

Copy link
Copy Markdown

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

Issue Details

null

Author:IDisposable
Assignees:-
Labels:

area-System.Collections, community-contribution

Milestone:-

@IDisposable

IDisposable commented Jul 30, 2023

Copy link
Copy Markdown
ContributorAuthor

Performance tests.

BenchmarkDotNet=v0.13.2.2052-nightly, OS=Windows 11 (10.0.22631.2115)
Intel Core i7-10875H CPU 2.30GHz, 1 CPU, 16 logical and 8 physical cores
.NET SDK=8.0.100-preview.7.23322.33
[Host] : .NET 8.0.0 (8.0.23.32106), X64 RyuJIT AVX2
Job-SVXVNR : .NET 8.0.0 (42.42.42.42424), X64 RyuJIT AVX2
Job-CESATQ : .NET 8.0.0 (42.42.42.42424), X64 RyuJIT AVX2
Job-YVAYLV : .NET 8.0.0 (42.42.42.42424), X64 RyuJIT AVX2
PowerPlanMode=00000000-0000-0000-0000-000000000000 Arguments=/p:EnableUnsafeBinaryFormatterSerialization=true IterationTime=250.0000 ms MaxIterationCount=20 MinIterationCount=15 WarmupCount=1 
MethodJobToolchainCountMeanErrorStdDevMedianMinMaxRatioMannWhitney(2ms)RatioSDGen0Gen1Gen2AllocatedAlloc Ratio
ToFrozenDictionaryJob-SVXVNRTrait Based101.233 μs0.0240 μs0.0247 μs1.241 μs1.183 μs1.279 μs0.99Same0.020.2038--1.68 KB1.00
ToFrozenDictionaryJob-CESATQBaseline101.250 μs0.0246 μs0.0242 μs1.257 μs1.210 μs1.281 μs1.00Base0.000.2056--1.68 KB1.00
ToFrozenDictionaryJob-YVAYLVFaster Freeze101.225 μs0.0244 μs0.0280 μs1.215 μs1.190 μs1.260 μs0.98Same0.030.2031--1.67 KB1.00
ToFrozenDictionaryJob-SVXVNRTrait Based1007.263 μs0.1453 μs0.1554 μs7.286 μs7.035 μs7.590 μs0.99Same0.031.42450.0297-11.83 KB1.00
ToFrozenDictionaryJob-CESATQBaseline1007.307 μs0.1418 μs0.1393 μs7.366 μs7.068 μs7.471 μs1.00Base0.001.44620.0284-11.83 KB1.00
ToFrozenDictionaryJob-YVAYLVFaster Freeze1007.461 μs0.1212 μs0.1134 μs7.504 μs7.253 μs7.637 μs1.02Same0.021.42840.0292-11.82 KB1.00
ToFrozenDictionaryJob-SVXVNRTrait Based100068.360 μs1.0448 μs0.9773 μs68.455 μs66.576 μs69.596 μs0.98Same0.0211.17022.6596-92.64 KB1.00
ToFrozenDictionaryJob-CESATQBaseline100069.919 μs0.8861 μs0.7399 μs70.078 μs68.216 μs70.834 μs1.00Base0.0011.16072.5112-92.64 KB1.00
ToFrozenDictionaryJob-YVAYLVFaster Freeze100067.473 μs1.1315 μs1.1620 μs67.719 μs65.659 μs69.484 μs0.97Same0.0211.07592.6371-92.63 KB1.00
ToFrozenDictionaryJob-SVXVNRTrait Based100001,104.651 μs4.3610 μs3.6416 μs1,104.166 μs1,098.515 μs1,112.397 μs1.00Same0.01148.4375148.4375148.4375904.43 KB1.00
ToFrozenDictionaryJob-CESATQBaseline100001,108.193 μs10.2913 μs8.0347 μs1,109.215 μs1,087.775 μs1,123.516 μs1.00Base0.00145.8333145.8333145.8333904.43 KB1.00
ToFrozenDictionaryJob-YVAYLVFaster Freeze100001,093.550 μs12.1788 μs10.1698 μs1,094.617 μs1,064.160 μs1,107.952 μs0.99Same0.01145.8333145.8333145.8333904.42 KB1.00

This will cost one extra `HashSet<string>` and one extra `SubstringComparer` to be allocated, but might make the code run faster.
Use the GSW strategy for virtual flattening
@IDisposable

Copy link
Copy Markdown
ContributorAuthor

This was a fantastic learning experience... This gained, at most, 3% performance without adversely impacting the allocation patterns and helped me learn the GSW pattern's application other places we want to eliminate virtual and delete overheads.

@IDisposable
IDisposable marked this pull request as ready for review July 30, 2023 12:09
@danmoseley

Copy link
Copy Markdown
Contributor

What is GSW pattern in this context? Maybe i missed it.

@IDisposable

Copy link
Copy Markdown
ContributorAuthor

What is GSW pattern in this context?

Using a GenericSpecializedWrapper to "pass in" the explicit implementation details at template declaration time as a struct that allows the compile to devirtualize all the interface methods. I saw it in the various frozen set implementations.

Replace ISubstringComparer with ISubstringEqualityComparer as that's more indicative of the interface it's exposing, and rename everything derived from that.
Fixed the implementation of FullStringEqualityComparer to not actually use the slice ReadOnlySpan(s) in the Equals and GetHashCode specializations.
Added comments for the SubstringEquality classes
Renamed the files for the specialization of the comparers.
Fixed the unit tests under debug builds.
Extended the test suite data for the KeyAnalyzer tests to exercise using the data in FrozenFromKnownValuesTests.
@IDisposable

Copy link
Copy Markdown
ContributorAuthor

I've done another pass to clean up the documentation and make it a little cleaner.

@IDisposable

Copy link
Copy Markdown
ContributorAuthor

Superseded by PR #89863

@ghostghost locked as resolved and limited conversation to collaborators Sep 1, 2023
@IDisposable
IDisposable deleted the trait-based branch February 15, 2025 20:05
Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-System.Collectionscommunity-contributionIndicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@IDisposable@danmoseley@eiriktsarpalis