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.
Go version
go1.21.2
What did you do?
Compile the following snippet:
What did you expect to see?
I would expect it to compile to something like:
I expect to see the following:
makesliceof a given length and capacity. The elements within the length need not be explicitly zeroed (since it can be provably overwritten).appendcall in the loop be essentially rewritten as an index operation, thus avoiding a call toruntime.growslicein every iteration of the loop.The conversation of
inttouintis 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.