What version of Go are you using (go version)?
$ go version
go version go1.21.4 linux/amd64
Does this issue reproduce with the latest release?
Yes
What did you do?
package main
import "testing"
var n = 1024 * 1024 * 16
type Large = int
var r1 []Large
var r2 []Large
func Benchmark_CompactFunc(b *testing.B) {
ss1 := make([]Large, n)
b.ResetTimer()
for i := 0; i < b.N; i++ {
r1 = CompactFunc(ss1, func(a, b Large) bool {return a == b})
}
}
func Benchmark_CompactFunc_2(b *testing.B) {
ss1 := make([]Large, n)
b.ResetTimer()
for i := 0; i < b.N; i++ {
r2 = CompactFunc_2(ss1, func(a, b Large) bool {return a == b})
}
}
func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S {
if len(s) < 2 {
return s
}
i := 1
for k := 1; k < len(s); k++ {
if !eq(s[k], s[k-1]) {
if i != k {
s[i] = s[k]
}
i++
}
}
clear(s[i:]) // zero/nil out the obsolete elements, for GC
return s[:i]
}
var global bool
func CompactFunc_2[S ~[]E, E any](s S, eq func(E, E) bool) S {
global = true // This is the only difference
if len(s) < 2 {
return s
}
i := 1
for k := 1; k < len(s); k++ {
if !eq(s[k], s[k-1]) {
if i != k {
s[i] = s[k]
}
i++
}
}
clear(s[i:]) // zero/nil out the obsolete elements, for GC
return s[:i]
}
What did you expect to see?
Similar performance for the specified test case.
What did you see instead?
Benchmark result shows CompactFunc_2 is (about 15%) slower, which is quite confusing.
goos: linux
goarch: amd64
pkg: example.com
cpu: Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz
Benchmark_CompactFunc-4 19 66914978 ns/op
Benchmark_CompactFunc_2-4 18 75483657 ns/op
What version of Go are you using (
go version)?Does this issue reproduce with the latest release?
Yes
What did you do?
What did you expect to see?
Similar performance for the specified test case.
What did you see instead?
Benchmark result shows
CompactFunc_2is (about 15%) slower, which is quite confusing.