2
新的 exp/slices 包大部分比较函数都比较慢
source link: https://www.v2ex.com/t/822599
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
package main
import (
"runtime"
"testing"
"golang.org/x/exp/slices"
)
var (
aa = make([]runtime.MemStats, 1)
bb = make([]runtime.MemStats, 1)
)
func Benchmark1(b *testing.B) {
for i := 0; i < b.N; i++ {
slices.Equal(aa, bb)
}
}
func Benchmark2(b *testing.B) {
for i := 0; i < b.N; i++ {
Equal(aa, bb)
}
}
func Benchmark3(b *testing.B) {
for i := 0; i < b.N; i++ {
Equal2(aa, bb)
}
}
func Equal[E comparable](s1, s2 []E) bool {
if len(s1) != len(s2) {
return false
}
for i := range s1 {
if s1[i] != s2[i] {
return false
}
}
return true
}
func Equal2[E comparable](s1, s2 []E) bool {
if len(s1) != len(s2) {
return false
}
for i := 0; i < len(s1); i++ {
if s1[i] != s2[i] {
return false
}
}
return true
}
/*
cpu: AMD Ryzen 5 2500U with Radeon Vega Mobile Gfx
Benchmark1-8 638925 1652 ns/op 0 B/op 0 allocs/op
Benchmark2-8 5131083 221.2 ns/op 0 B/op 0 allocs/op
Benchmark3-8 5423184 229.6 ns/op 0 B/op 0 allocs/op
*/
原因就是代码使用 range 来带值遍历, 这样会进行复制数据
这个包里不少函数都是这样的, 有兄弟愿意的话可以去官方提交代码或提个意见
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK