slice删除元素的性能对比
作者:互联网
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
原文:
https://www.jianshu.com/p/d276aa7300d1
标签:slice,删除,testing,main6,bench,test,go,ns,对比 来源: https://blog.51cto.com/5660061/2426094