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

How to Efficiently Deep Copy a Slice in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 18:15:151035browse

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...)

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

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

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
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).

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

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!

Statement:
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