From 9c9386d2a8c041f3c1f19469b47414c419f7d534 Mon Sep 17 00:00:00 2001 From: Nicolas Lacasse Date: Fri, 8 Feb 2019 12:59:04 -0800 Subject: CopyObjectOut should allocate a byte slice the size of the encoded object. This adds an extra Reflection call to CopyObjectOut, but avoids many small slice allocations if the object is large, since without this we grow the backing slice incrementally as we encode more data. PiperOrigin-RevId: 233110960 Change-Id: I93569af55912391e5471277f779139c23f040147 --- pkg/sentry/usermem/usermem.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pkg/sentry/usermem/usermem.go b/pkg/sentry/usermem/usermem.go index 1d6c0b4d6..75ac4d22d 100644 --- a/pkg/sentry/usermem/usermem.go +++ b/pkg/sentry/usermem/usermem.go @@ -181,7 +181,11 @@ func CopyObjectOut(ctx context.Context, uio IO, addr Addr, src interface{}, opts Addr: addr, Opts: opts, } - return w.Write(binary.Marshal(nil, ByteOrder, src)) + // Allocate a byte slice the size of the object being marshaled. This + // adds an extra reflection call, but avoids needing to grow the slice + // during encoding, which can result in many heap-allocated slices. + b := make([]byte, 0, binary.Size(src)) + return w.Write(binary.Marshal(b, ByteOrder, src)) } // CopyObjectIn copies a fixed-size value or slice of fixed-size values from -- cgit v1.2.3