Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/compile: optimize struct reset logic #52373

Open
dsnet opened this issue Apr 15, 2022 · 2 comments
Open

cmd/compile: optimize struct reset logic #52373

dsnet opened this issue Apr 15, 2022 · 2 comments
Labels
compiler/runtime Issues related to the Go compiler and/or runtime. NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one. Performance
Milestone

Comments

@dsnet
Copy link
Member

dsnet commented Apr 15, 2022

Consider the following:

type S struct {
	Large [8]int
	Small int
}

var s = new(S)

func BenchmarkResetA(b *testing.B) {
	for i := 0; i < b.N; i++ {
		*s = S{Large: s.Large}
	}
}

func BenchmarkResetB(b *testing.B) {
	for i := 0; i < b.N; i++ {
		s.Small = 0
	}
}

Performance:

BenchmarkResetA
BenchmarkResetA-24    	131323767	         9.117 ns/op
BenchmarkResetB
BenchmarkResetB-24    	1000000000	         0.2167 ns/op

Both snippets are semantically equivalent, but ResetB is much faster.
However, ResetA is common in reset logic where the intention is to reset all fields except a few select fields. This pattern is more maintainable since it properly resets the struct even if new fields are added to it later on.

The compiler should recognize the pattern exhibited in ResetA and avoid the unnecessary copy of s.Large = s.Large.

@mvdan
Copy link
Member

mvdan commented Apr 16, 2022

dup of #24386?

@thanm thanm added the NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one. label Apr 18, 2022
@thanm
Copy link
Contributor

thanm commented Apr 18, 2022

Also possible related, #24416

@seankhliao seankhliao added the compiler/runtime Issues related to the Go compiler and/or runtime. label Aug 20, 2022
@seankhliao seankhliao added this to the Unplanned milestone Aug 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
compiler/runtime Issues related to the Go compiler and/or runtime. NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one. Performance
Projects
None yet
Development

No branches or pull requests

4 participants