Junior — Middle
Andmete edastamisel funktsioonile: mis on mälu kasutamise osas tõhusam — massiiv või lõik?
sobes.tech AI
Vastus AI-lt
In Go, arrays have a fixed size and are stored entirely in memory, while slices are structures that contain a pointer to an array, a length, and a capacity.
From a memory usage perspective:
- Array: occupies exactly as much memory as needed for all elements, size is known at compile time.
- Slice: itself occupies little memory (three words: pointer, length, capacity), but points to an array that holds the data.
When passing to a function:
- If an array is passed, it is copied in its entirety, which can be costly in terms of memory and time for large arrays.
- If a slice is passed, only the slice structure (pointer + length + capacity) is copied, and the data remains in the original array, so no data copying occurs.
Therefore, passing a slice is more efficient in terms of memory usage and performance, especially for large datasets.
Example:
func processArray(arr [1000]int) {
// copies the entire array
}
func processSlice(s []int) {
// copies only the slice structure
}
func main() {
var a [1000]int
processArray(a) // costly
processSlice(a[:]) // efficient
}