Created
August 31, 2022 09:22
-
-
Save Deleplace/1dddcb379ceb6f51e53fa16ae6548ba9 to your computer and use it in GitHub Desktop.
Benchmark for a generic func: simple loop vs. calling slices.Index
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On my workstation: