Skip to content

Commit

Permalink
Add benchmark and optimize ContainsDuplicates (#1575)
Browse files Browse the repository at this point in the history
  • Loading branch information
BrendanChou authored May 23, 2024
1 parent 212456e commit 521dc27
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
13 changes: 8 additions & 5 deletions protocol/lib/collections.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ import (

// ContainsDuplicates returns true if the slice contains duplicates, false if not.
func ContainsDuplicates[V comparable](values []V) bool {
seenValues := make(map[V]bool)
for _, val := range values {
if _, exists := seenValues[val]; exists {
// Store each value as a key in the mapping.
seenValues := make(map[V]struct{}, len(values))
for i, val := range values {
// Add the value to the mapping.
seenValues[val] = struct{}{}

// Return early if the size of the mapping did not grow.
if len(seenValues) <= i {
return true
}

seenValues[val] = true
}

return false
Expand Down
22 changes: 20 additions & 2 deletions protocol/lib/collections_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,24 @@ func TestDedupeSlice(t *testing.T) {
}
}

func BenchmarkContainsDuplicates_True(b *testing.B) {
var result bool
input := []uint32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
for i := 0; i < b.N; i++ {
result = lib.ContainsDuplicates(input)
}
require.True(b, result)
}

func BenchmarkContainsDuplicates_False(b *testing.B) {
var result bool
input := []uint32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
for i := 0; i < b.N; i++ {
result = lib.ContainsDuplicates(input)
}
require.False(b, result)
}

func TestContainsDuplicates(t *testing.T) {
tests := map[string]struct {
input []uint32
Expand All @@ -80,11 +98,11 @@ func TestContainsDuplicates(t *testing.T) {
input: []uint32{},
expected: false,
},
"True": {
"False": {
input: []uint32{1, 2, 3, 4},
expected: false,
},
"False": {
"True": {
input: []uint32{1, 2, 3, 4, 3},
expected: true,
},
Expand Down

0 comments on commit 521dc27

Please sign in to comment.