funcContains(array interface{}, val interface{})(index int) { index = -1 switch reflect.TypeOf(array).Kind() { case reflect.Slice: { s := reflect.ValueOf(array) for i := 0; i < s.Len(); i++ { if reflect.DeepEqual(val, s.Index(i).Interface()) { index = i return } } } } return }
funcStringsContains(array []string, val string)(index int) { index = -1 for i := 0; i < len(array); i++ { if array[i] == val { index = i return } } return }
使用 testing 包来测试性能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import"testing"
funcBenchmarkContains(b *testing.B) { sa := []string{"q", "w", "e", "r", "t"} b.ResetTimer() for n := 0; n < b.N; n++ { Contains(sa, "r") } }
funcBenchmarkStringsContains(b *testing.B) { sa := []string{"q", "w", "e", "r", "t"} b.ResetTimer() for n := 0; n < b.N; n++ { StringsContains(sa, "r") } }
运行
1 2 3 4 5 6 7 8 9
$ go test -bench=.
goos: darwin goarch: amd64 pkg: github.com/wxnacy/wgo/arrays BenchmarkContains-8 2000000 635 ns/op BenchmarkStringsContains-8 100000000 20.3 ns/op PASS ok github.com/wxnacy/wgo/arrays 4.027s