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

PHPz
Release: 2024-02-12 14:21:06
forward
467 people have browsed it

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...)
Copy after login

Compared

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!