Home > Backend Development > Golang > What are the Most Concise and Performant Ways to Deep Copy Slices in Go?

What are the Most Concise and Performant Ways to Deep Copy Slices in Go?

Patricia Arquette
Release: 2024-12-23 19:26:15
Original
1041 people have browsed it

What are the Most Concise and Performant Ways to Deep Copy Slices in Go?

Concision and Performance in Deep Copying Slices

When working with slices in Go, you may encounter the need to deep copy a slice, ensuring that changes to the copy do not affect the original slice. This article explores two concise and well-performing methods for achieving this.

One established technique is to use the append function:

copy := append([]T{}, orig...)
Copy after login

However, an alternative method using the built-in copy function has emerged:

cpy := make([]T, len(orig))
copy(cpy, orig)
Copy after login

The documentation for the copy function states that it copies elements from a source slice to a destination slice, overlapping if necessary. It returns the number of elements copied, which is limited by the lengths of both slices.

Note: Both methods copy only the values in the slice. If the slice contains pointers or structs with pointer fields, these pointers will continue to point to the same values as in the original slice.

Benchmark Results:

To assess the performance of these methods, a benchmark was conducted:

BenchmarkCopy     100000         24724 ns/op
BenchmarkAppend   100000         24967 ns/op
Copy after login

As you can see, both approaches have very similar performance.

Assembly Analysis:

Examining the assembly generated for each method reveals that both call either runtime.growslice or runtime.makeslice, which are likely responsible for performing any zero-filling required for the new slice.

The above is the detailed content of What are the Most Concise and Performant Ways to Deep Copy Slices in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template