Skip to content

cmd/compile: strange performance difference between two implementations #49785

@zigo101

Description

@zigo101

What version of Go are you using (go version)?

$ go version
go version go1.17.3 linux/amd64

Does this issue reproduce with the latest release?

Yes

What did you do?

package pointers

import "testing"

const N = 10000

type T struct {
	x int
}

//go:noinline
func f(t *T) {
	t.x = 0
	for i := 0; i < N; i++ {
		t.x += i
	}
}

//go:noinline
func g(t *T) {
	var x = 0
	for i := 0; i < N; i++ {
		x += i
	}
	t.x = x
}

func Benchmark_f(b *testing.B) {
	var t = &T{}
	for i := 0; i < b.N; i++ { f(t) }
}

func Benchmark_g(b *testing.B) {
	var t = &T{}
	for i := 0; i < b.N; i++ { g(t) }
}

What did you expect to see?

Similar performances.

What did you see instead?

goos: linux
goarch: amd64
pkg: example.com
cpu: Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz
Benchmark_f-4   	   48352	     24403 ns/op
Benchmark_g-4   	  292581	      3956 ns/op

I checked the generated assembly instructions. Yes, they are different, but the complexities are similar. So it is some strange that the performance difference is so large.

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