Skip to content

Instantly share code, notes, and snippets.

@Deleplace
Created August 31, 2022 09:22
Show Gist options
  • Save Deleplace/1dddcb379ceb6f51e53fa16ae6548ba9 to your computer and use it in GitHub Desktop.
Save Deleplace/1dddcb379ceb6f51e53fa16ae6548ba9 to your computer and use it in GitHub Desktop.
Benchmark for a generic func: simple loop vs. calling slices.Index
package bench
import (
"testing"
"golang.org/x/exp/slices"
)
func BenchmarkRemoveFirstByValue(b *testing.B) {
items := []string{"a", "b", "c", "d", "e", "f", "g", "h"}
for i := 0; i < b.N; i++ {
items = removeFirstByValue(items, "d")
items = slices.Insert(items, 3, "d")
}
}
func BenchmarkRemoveFirstByValueIndex(b *testing.B) {
items := []string{"a", "b", "c", "d", "e", "f", "g", "h"}
for i := 0; i < b.N; i++ {
items = removeFirstByValueIndex(items, "d")
items = slices.Insert(items, 3, "d")
}
}
func removeFirstByValue[T comparable](items []T, x T) []T {
for i, y := range items {
if y == x {
return slices.Delete(items, i, i+1)
}
}
return items
}
func removeFirstByValueIndex[S ~[]T, T comparable](items S, x T) S {
if i := slices.Index(items, x); i != -1 {
return slices.Delete(items, i, i+1)
}
return items
}
@Deleplace
Copy link
Author

On my workstation:

% go test -bench=. -benchtime=30s
goos: darwin
goarch: amd64
cpu: VirtualApple @ 2.50GHz
BenchmarkRemoveFirstByValue-10         	1000000000	        28.47 ns/op
BenchmarkRemoveFirstByValueIndex-10    	1000000000	        28.90 ns/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment