Home  >  Article  >  Backend Development  >  Is it always faster to use copy instead of append on a slice?

Is it always faster to use copy instead of append on a slice?

PHPz
PHPzforward
2024-02-12 14:21:06469browse

Is it always faster to use copy instead of append on a slice?

Question content

When iteratively growing a slice, it is easy to see why allocating the size first (if it is known) is more efficient than using the append function, because later The operator will decide whether to increase the size slice capacity at each iteration. But I'm curious to know if using the additional variadic form is less efficient than using the make/copy construct when concatenating two large slices in a non-iterative manner. For example (assuming sl1 and sl2 are of type []int)

sl = append(sl, sl2...)

Compared

nsl = make([]int, len(sl) + len(sl2))
i := copy(nsl, sl)
copy(nsl[i], sl2)
sl = nsl

I would have thought that the first form (more readable) would still work, since I expected there would still only be a capacity change (based on the number of arguments to the append call). Am I right to think so?

Solution

append and copy use the same underlying copy primitive.

If the target slice has sufficient capacity, append will not allocate memory.

append Code is easier to read.

The above is the detailed content of Is it always faster to use copy instead of append on a slice?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete