Skip to content

Instantly share code, notes, and snippets.

@honmaple
Created February 11, 2022 06:45
Show Gist options
  • Save honmaple/b28177cb31c288593773df4983e7a5ba to your computer and use it in GitHub Desktop.
Save honmaple/b28177cb31c288593773df4983e7a5ba to your computer and use it in GitHub Desktop.
test function slice param
package main
import (
"testing"
)
type myStruct struct {
list []string
}
func BenchmarkSliceNoPointer(b *testing.B) {
b.ReportAllocs()
slice := make([]string, 1000)
for i := 0; i < b.N; i++ {
testNoPointer(slice)
}
}
func BenchmarkSlicePointer(b *testing.B) {
b.ReportAllocs()
slice := make([]string, 1000)
for i := 0; i < b.N; i++ {
testPointer(&slice)
}
}
func BenchmarkSliceWithStruct(b *testing.B) {
b.ReportAllocs()
slice := make([]string, 1000)
s := &myStruct{list: slice}
for i := 0; i < b.N; i++ {
testPointerWithStruct(s)
}
}
func testNoPointer(list []string) {
for i := 0; i < 100; i++ {
list[i] = "test string"
}
}
func testPointer(list *([]string)) {
for i := 0; i < 100; i++ {
(*list)[i] = "test string"
}
}
func testPointerWithStruct(s *myStruct) {
for i := 0; i < 100; i++ {
s.list[i] = "test string"
}
}
@honmaple
Copy link
Author

──╼ go test -bench .
goos: darwin
goarch: amd64
pkg: my-test
BenchmarkSliceNoPointer-8    	37524774	        30.57 ns/op	       0 B/op	       0 allocs/op
BenchmarkSlicePointer-8      	11967490	       100.5 ns/op	       0 B/op	       0 allocs/op
BenchmarkSliceWithStruct-8   	11358862	       110.0 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	my-test	5.065s

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