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=.
成都创新互联主营明山网站建设的网络公司,主营网站建设方案,成都app软件开发,明山h5微信小程序定制开发搭建,明山网站营销推广欢迎明山等地区企业咨询
输出:
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
文章题目:slice删除元素的性能对比
链接URL:http://scjbc.cn/article/goeisj.html