Junior — Middle
Is it possible to achieve faster iteration over a slice compared to a Map in programming languages?
sobes.tech AI
Answer from AI
Yes, iterating over a slice in Go is usually faster than iterating over a Map because a slice is a sequential array of elements, whereas a Map is a hash table with a more complex structure.
Iteration over a slice occurs sequentially in memory, which is well cached by the processor, whereas a Map requires hash calculations and can have an arbitrary traversal order.
Example of iterating over a slice:
slice := []int{1, 2, 3, 4, 5}
for _, v := range slice {
fmt.Println(v)
}
Iteration over a Map:
m := map[string]int{"a":1, "b":2}
for k, v := range m {
fmt.Println(k, v)
}
Thus, if speed and order are important, it is better to use slices.