Home > Backend Development > Golang > How to Efficiently Deep Copy a Slice in Go?

How to Efficiently Deep Copy a Slice in Go?

Barbara Streisand
Release: 2024-12-09 18:15:15
Original
1058 people have browsed it

How to Efficiently Deep Copy a Slice in Go?

Deep Copying a Slice in Go

In Go, creating a deep copy of a slice efficiently is essential to prevent modifications to the original backing array. One commonly used approach involves using a slice literal and the append function:

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

However, there is an alternative method that utilizes the built-in copy function:

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

This approach retrieves the required storage and directly copies elements from the source to the destination using the copy built-in function. According to the documentation:

func copy(dst, src []Type) int
Copy after login
The copy built-in function copies elements from a source slice into a
destination slice. ... Copy returns the number of elements copied, which will be the minimum
of len(src) and len(dst).
Copy after login

Note:

Both methods perform a shallow copy, meaning the pointers or struct fields within the slice will still point to the original values.

Benchmark:

Comparing the performance of both techniques yields similar results:

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

This suggests that both approaches are equally suitable for deep copying slices in Go. However, the copy function approach may be slightly more efficient when dealing with large slices.

The above is the detailed content of How to Efficiently Deep Copy a Slice 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