Skip to content

cmd/compile: unexpected benchmark results #64328

Description

@zigo101

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Performancecompiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions