'Does copy() function more efficient than slice[start:end] operators? [duplicate]
My goal is to validate whether the tutorial given by w3schools is true, I use w3schools#Memory Efficinecy as reference.
I quote from the tutorial
If the array is large and you need only a few elements, it is better to copy those elements using the copy() function.
package main
import ("fmt")
func main() {
numbers := []int{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
// Original slice
fmt.Printf("numbers = %v\n", numbers)
fmt.Printf("length = %d\n", len(numbers))
fmt.Printf("capacity = %d\n", cap(numbers))
// Create copy with only needed numbers
neededNumbers := numbers[:len(numbers)-10]
numbersCopy := make([]int, len(neededNumbers))
copy(numbersCopy, neededNumbers)
fmt.Printf("numbersCopy = %v\n", numbersCopy)
fmt.Printf("length = %d\n", len(numbersCopy))
fmt.Printf("capacity = %d\n", cap(numbersCopy))
}
The problem is neededNumbers := numbers[:len(numbers)-10]
already copied the elements from the numbers
slice. I believe copy()
is unnecessary in this case.
From my knowledge, you can copy with an operator or copy() function:
- newSlice := oldSlice[start:end]
- copy(dst, src) -> however we need to initialize empty slice first newSlice := make(type, capacity)
So, how does copy() supposedly to be more memory efficient if it takes 2 steps to achieve the same thing?
Solution 1:[1]
If the array is large and you need only a few elements, it is better to copy those elements using the copy() function. w3schools#Memory Efficiency
New in Go 1.18. In some cases, for a small substring of a much larger string use strings.Clone
.
For example,
shortString := strings.Clone(longString[42 : 42+7])
The same principles apply to a small subslice of a much larger slice.
Note: If the type of the slice element is a pointer or a struct with pointer fields, which need to be garbage collected, there is a potential memory leak problem with a subslice: some elements with values are still referenced by the full slice underlying array and thus can not be collected unless the elements are set to nil.
added in go1.18
func Clone(s string) string
Clone returns a fresh copy of s. It guarantees to make a copy of s into a new allocation, which can be important when retaining only a small substring of a much larger string. Using Clone can help such programs use less memory. Of course, since using Clone makes a copy, overuse of Clone can make programs use more memory. Clone should typically be used only rarely, and only when profiling indicates that it is needed. For strings of length zero the string "" will be returned and no allocation is made.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |