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
NeedsInvestigation Performance

Comments

@dsnet
Copy link
Member

@dsnet 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 mvdan commented Apr 16, 2022

dup of #24386?

@thanm thanm added the NeedsInvestigation label Apr 18, 2022
@thanm
Copy link
Contributor

@thanm thanm commented Apr 18, 2022

Also possible related, #24416

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
NeedsInvestigation Performance
Projects
None yet
Development

No branches or pull requests

3 participants