Append essentially does the following:
http://play.golang.org/p/WFaGXhFvlcMy guess is that there are three reasons to have cloneBytes:
1. If you notice the created new slice in append has extra capacity (to
be used on further appends), but it seems this use case is meant to copy a
slice (no extra space needed)
2. The comparison inside cloneBytes is simpler than in append (compare
to 0), and may get optimized out after inlining (the calling code already
checks for nil in some points)
3. In the real append, the amount of extra space is not a constant
number of additional elements or a constant scale, but is chosen based on
slice size resulting in at least one extra branch in the code
In the CL referenced it looks like the purpose of cloneBytes is to make a
copy of the data that is not going to be appended to. Although #2 and #3
may be able to go away in certain places with a good compiler, #1 will
always be true, as append will always allocated some extra slots in case of
future appends, to avoid the allocations and copies involved in appending
to a full slice.
On Monday, March 25, 2013 6:09:56 PM UTC-7, kortschak wrote:I was perusing the current code reviews and noticed that a cloneBytes
function has been included in the linked CL. Can someone tell me why use
that rather than append([]byte(nil), b...) since as far as I can see it
has the same behaviour?
Is it because of the fast path where b == nil?
func cloneBytes(b []byte) []byte {
if b == nil {
return nil
} else {
c := make([]byte, len(b))
copy(c, b)
return c
}
}
https://codereview.appspot.com/7962044/ --
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit
https://groups.google.com/groups/opt_out.