Replace unused return values from Add() calls with add() and optimize loop traversal#170
Merged
Merged
Conversation
ryclarke
suggested changes
Apr 23, 2026
| prevLen := len(*s) | ||
| for _, val := range v { | ||
| (*s)[val] = struct{}{} | ||
| func (s *threadUnsafeSet[T]) Append(vs ...T) int { |
Contributor
There was a problem hiding this comment.
It looks to me like an append() is needed as a counterpart to add(), since the optimized logic is used in multiple places:
func (s *threadUnsafeSet[T]) Append(vs ...T) {
prevLen := s.Cardinality()
s.append(v)
return prevLen != s.Cardinality()
}
func (s *threadUnsafeSet[T]) append(vs ...T) {
for i := range vs {
s.add(vs[i])
}
}
// s.append can then be used in JSON/BSON unmarshaling2a24e45 to
9b7b974
Compare
ryclarke
reviewed
Apr 24, 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.
Key Changes
This pull request makes two main performance optimizations:
1. Replace
Add()withadd()when return values are not usedWhen the boolean return value from
Add()is not needed, the code now calls the privateadd()method instead. This eliminates unnecessarylen()calls:NewThreadUnsafeSet():2. Replace value-based slice iteration with index-based loops
Instead of using
for _, val := range slice, the code now usesfor i := range sliceto access elements by index:Append():Files Modified
bench_test.go- Added benchmarks forNewSet(),NewThreadUnsafeSet(),Append(), and other methodsset.go- OptimizedNewSet(),NewThreadUnsafeSet(), and related functions to useadd()methodthreadunsafe.go- UpdatedAdd(),Append(), and unmarshal methods to use index-based iteration and privateadd()callsAdditional Improvements
vals→vs,item→ (index-based),i→is(for slices)Add()and unmarshal methodsBenchmark
Before
After