Reputation: 3561
Suppose I have the following code:
arr := make([][]byte, 10000)
for i := range arr {
arr[i] = make([]byte, 10000)
}
Is it faster to iterate over the array like this?
for row := len(arr) {
for col := len(arr[0]) {
// access arr[col][row]
}
}
Or like this?
for col:= len(arr[0]) {
for row := len(arr) {
// access arr[col][row]
}
}
Upvotes: 1
Views: 347
Reputation: 417672
The second version allows to perform less indexing: you index once and you get a row. Iterating over a row can be done by indexing the "inner" slice only.
So when iterating over a slice of slices, always loop first by the outer slice, you index it once and you get an inner slice. You can iterate over it by indexing only the inner slice (no need to index the outer always).
This also results in sequential memory access which may result in further optimization by the compiler and runtime.
So do it like this:
for _, row := range arr {
for _, value := range row {
// Use value
}
}
Doing the other way (when you increase the index of the inner slice first), you always have to use double indexing.
Upvotes: 3