Skip to content

Instantly share code, notes, and snippets.

@ego008
Created May 19, 2022 02:44
Show Gist options
  • Save ego008/a5e67e8c74a7ac9be92f46d264d63315 to your computer and use it in GitHub Desktop.
Save ego008/a5e67e8c74a7ac9be92f46d264d63315 to your computer and use it in GitHub Desktop.
Golang Slice Contains Benchmark
package main
import (
"fmt"
"strconv"
"testing"
)
/**
@author: golangNote
@since: 2022/5/18
@desc: go test -v contain_test.go -bench "Benchmark" -benchmem
@source: https://golangnote.com/topic/309.html
**/
var (
sliceLen = 15
sliceStr = make([]string, sliceLen)
sliceInt = make([]int, sliceLen)
mapStr = map[string]struct{}{}
mapInt = map[int]struct{}{}
)
func init() {
for i := 0; i < sliceLen; i++ {
is := strconv.Itoa(i)
sliceStr[i] = is
sliceInt[i] = i
mapStr[is] = struct{}{}
mapInt[i] = struct{}{}
}
fmt.Println("sliceLen:", sliceLen)
}
func ContainsGeneric[T comparable](slice []T, element T) bool {
for _, e := range slice {
if e == element {
return true
}
}
return false
}
func ContainsStr(slice []string, element string) bool {
for _, e := range slice {
if e == element {
return true
}
}
return false
}
func ContainsInt(slice []int, element int) bool {
for _, e := range slice {
if e == element {
return true
}
}
return false
}
func ContainsMapStr(mp map[string]struct{}, element string) bool {
_, ok := mp[element]
return ok
}
func ContainsMapInt(mp map[int]struct{}, element int) bool {
_, ok := mp[element]
return ok
}
func BenchmarkContainsGenericStr(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
var has bool
for j := range sliceStr {
has = ContainsGeneric(sliceStr, sliceStr[j])
}
_ = has
}
}
func BenchmarkContainsGenericInt(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
var has bool
for j := range sliceInt {
has = ContainsGeneric(sliceInt, sliceInt[j])
}
_ = has
}
}
func BenchmarkContainsStr(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
var has bool
for j := range sliceStr {
has = ContainsStr(sliceStr, sliceStr[j])
}
_ = has
}
}
func BenchmarkContainsInt(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
var has bool
for j := range sliceInt {
has = ContainsInt(sliceInt, sliceInt[j])
}
_ = has
}
}
func BenchmarkContainsMapStr(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
var has bool
for j := range mapStr {
has = ContainsMapStr(mapStr, j)
}
_ = has
}
}
func BenchmarkContainsMapInt(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
var has bool
for j := range mapInt {
has = ContainsMapInt(mapInt, j)
}
_ = has
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment