Repository navigation
Do not check IsEmpty for every item in ConcurrentBag.Clear - #704
Merged
Merged
Conversation
TryTake returns false once the bag is empty, so the IsEmpty check before every TryTake is redundant, and IsEmpty takes the bag's global lock.
This was referenced Oct 12, 2026
This was referenced Oct 14, 2026
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
The
ConcurrentBag<T>.Clearpolyfill (.NET Framework / netstandard2.0) checkedIsEmptybefore everyTryTake. On .NET FrameworkIsEmptyfreezes the bag under its global lock, so it costs more than theTryTakeit guards.TryTakealready returnsfalseonce the bag is empty, so the loop is now:Same result, including when other threads add or take concurrently: both versions stop the first time the bag is observed empty.
Measurements
net48, Release, x64, Stopwatch around
Clearonly, best of 7, microseconds per call:Clearing an already empty bag is about 0.15 us slower, because a failing
TryTake(which tries to steal from other threads' lists) costs more thanIsEmpty. Guarding with oneIsEmptyup front would fix that case and make every other case pay for it, so I left it out.Tests
Added to
PolyfillTests_ConcurrentBag.cs: clearing bags of 0, 1, 2 and 1,000 items (IsEmpty,Count,ToArray,TryTake,TryPeekafterwards, clearing twice, and reuse after clearing); a bag filled from four threads, so that items live in several thread-local lists; null and default items.