package main import ( "testing" ) // 第一种 func BenchmarkMake(t *testing.B) { t.ResetTimer() origin := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := 0; i < t.N; i++ { target := make([]int, len(origin)) for _, item := range origin { if item != 6 { target = append(target, item) } } } } // 第二种 func BenchmarkReuse(t *testing.B) { t.ResetTimer() origin := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := 0; i < t.N; i++ { target := origin[:0] for _, item := range origin { if item != 6 { target = append(target, item) } } } } // 第三种 func BenchmarkEditOne(t *testing.B) { t.ResetTimer() origin := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := 0; i < t.N; i++ { for i := 0; i < len(origin); i++ { if origin[i] == 6 { origin = append(origin[:i], origin[i+1:]...) i-- // maintain the correct index } } } } // 第四种 func BenchmarkFuck(t *testing.B) { t.ResetTimer() origin := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := 0; i < t.N; i++ { for i := 0; i < len(origin); i++ { if origin[i] == 6 { tempV := origin[i] origin = append(append(origin[:i], origin[i+1:]...), tempV) //i-- // maintain the correct index } } } }
执行命令:go test main6_test.go -v -bench=.
输出:
E:\go_work_dir\test\x>go test main6_test.go -v -bench=.
goos: windows
goarch: amd64
BenchmarkMake-8 10000000 146 ns/op
BenchmarkReuse-8 100000000 10.9 ns/op
BenchmarkEditOne-8 200000000 7.69 ns/op
BenchmarkFuck-8 100000000 13.4 ns/op
PASS
ok command-line-arguments 8.592s
命令:go test main6_test.go -v -bench=. -benchtime=3s -benchmem
查看更多内容
原文:
https://www.jianshu.com/p/d276aa7300d1
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。