In Go, if I want to do something 500 times, but I don't need to use the index, is there a way to loop without allocating an integer?
Like:
for i := 0; i < 500; i++ {
PlayRandomGame()
}
I don't need or want to allocate i
there.
Nothing in that code requires i
to be allocated on the heap. It's likely either on the stack, freed when it goes out of scope, or in a register, and in either case not creating garbage. (If you're curious about how this is possible, the technique is called escape analysis.) You can see it in how TotalAlloc doesn't increase in this sample program:
package main
import (
"fmt"
"runtime"
)
func loop() {
for i := 0; i < 500; i++ {
}
}
func main() {
m1, m2 := new(runtime.MemStats), new(runtime.MemStats)
runtime.ReadMemStats(m1)
loop()
runtime.ReadMemStats(m2)
fmt.Println("TotalAlloc delta was", m2.TotalAlloc - m1.TotalAlloc)
}
A counter's necessary to make sure you do 500 iterations of a loop one way or the other, so even if you found some way to make the counter implied (r := make([]struct{}, 500); for range r {...}
, say), there'd be no variable name but still be a counter under the covers.
If you hate counters, you can use this:
for _ = range make([]struct{}, 500) {
PlayRandomGame()
}
But the variant with a counter is more idiomatic.