cmd/compile: avoid allocations for some return values #22081
Labels
compiler/runtime
Issues related to the Go compiler and/or runtime.
NeedsInvestigation
Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.
Performance
Milestone
A non-inlinable function that returns new memory always allocates it on the heap. For example, in the base64 package the
DecodeString
method returns a heap-allocated byte slice:func (enc *Encoding) DecodeString(s string) ([]byte, error)
It is common for this return value to have limited life, easily scoped to the stack:
For cases like this, the
DecodeString
method could have been made more efficient by writing in a style where the[]byte
was passed as an argument:func (enc *Encoding) AppendDecodeString(out []byte, s string) ([]byte, error)
No heap allocation is necessary for calling this version. This transformation has been manually applied in many places in the standard library, from the
Append*
functions in strconv toio.Reader
itself.The compiler could do this automatically.
For concrete methods, the original function signature can be satisfied by a wrapper function, that allocates the value on the heap and calls a variant where return values containing pointers are passed as "out" arguments. When compiling code that can keep the output on the stack, the caller can be modified to use the generated functions.
For example, the implementation of
DecodeString
is:Currently, escape analysis determines that
dbuf
escapes to the heap without ever seeing how the value is used. Instead, the compiler can split this function in two, an inlinable allocation function, and a body:Then the compiler can transform callers of
DecodeString
where the return value would fit on the stack to two calls toΨDecodeString
andΦDecodeString
. The first is inlined, determined not to escape and sodbuf
lives on the stack.The general analysis of can the Ψ allocation function be inlined, and how does it pass data dependencies to the Φ function could get complicated.
The text was updated successfully, but these errors were encountered: