Skip to content

cmd/compile: optimize struct reset logic #52373

@dsnet

Description

@dsnet

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.

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