Skip to content

cmd/compile: optimize append with string concatenation #56442

@dsnet

Description

@dsnet

Consider the following benchmark:

const prefix = "some sufficiently long prefix "
var something = "something"
const suffix = " some sufficiently long suffix"

var sink []byte

func BenchmarkNaive(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		sink = append(sink[:0], prefix+something+suffix...)
	}
}

There's a number of string concatenations going on, some from variables and others from constants,
which runs in:

BenchmarkNaive-24        	23387558	        45.20 ns/op	      80 B/op	       1 allocs/op

However, the benchmark is semantically equivalent to:

func BenchmarkOptimized(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		sink = append(append(append(sink[:0], prefix...), something...), suffix...)
	}
}

which runs in:

BenchmarkOptimized-24    	191343406	         6.218 ns/op	       0 B/op	       0 allocs/op

That is a 100% reduction in allocations, and a dramatic speedup.

The compiler should implicitly perform this transformation for me.

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