Skip to content

cmd/compile: pre-allocate a slice of provable length  #64595

Open
@dsnet

Description

@dsnet

Go version

go1.21.2

What did you do?

Compile the following snippet:

func transform(a []int) []uint {
	var b []uint
	for _, x := range a {
		b = append(b, uint(x))
	}
	return b
}

What did you expect to see?

I would expect it to compile to something like:

func transform(a []int) []uint {
	b := make([]uint, len(a), len(a) + ...) // where ... is some extra capacity to reproduce above behavior
	for i, x := range a {
		b[i] = uint(x)
	}
	return b
}

I expect to see the following:

  • An implicit call to makeslice of a given length and capacity. The elements within the length need not be explicitly zeroed (since it can be provably overwritten).
  • The append call in the loop be essentially rewritten as an index operation, thus avoiding a call to runtime.growslice in every iteration of the loop.

The conversation of int to uint is for demonstration, but the above optimization should be doable for any conversion that does not panic.

What did you see instead?

Right now, this compiles more or less to what you see in the original code snippet.

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