Junior — Middle
When passing data to a function: what is more memory-efficient — an array or a slice?
sobes.tech AI
Answer from AI
In Go, arrays have a fixed size and are stored entirely in memory, whereas slices are a structure that contains a pointer to an array, a length, and a capacity.
From a memory usage perspective:
- Array — occupies exactly enough memory for all elements, size is known at compile time.
- Slice — itself takes up a small amount of memory (three words: pointer, length, capacity), but points to an array that holds the data.
When passing to a function:
- If you pass an array, it is copied entirely, which can be costly in terms of memory and time for large sizes.
- If you pass a slice, 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) {
// only copies the slice structure
}
func main() {
var a [1000]int
processArray(a) // costly
processSlice(a[:]) // efficient
}