Answer the question
In order to leave comments, you need to log in
Reusing len() or caching into a variable?
IDEs in many other languages like PHP suggest that you should not use len() (or similar functions) in a for construct, as each iteration will recompute the length of the array.
I checked that if instead of len you insert your own function that outputs something, then it will be executed on each cycle:
kek := func() int {
fmt.Prinln("CALL")
return 10
}
for i := 0; i < kek(); i++ {
//
}
// 1:
for i := 0; i < len(data); i++ {
//
}
// 2:
dataLength := len(data)
for i := 0; i < dataLength; i++ {
//
}
Answer the question
In order to leave comments, you need to log in
With the help of this thing, you can see what it compiles into: https://github.com/badamczewski/PowerUp
But in general, len should simply return the length of the slice, which is written in the field, so there will not be much difference.
If you really have a slice that cannot change inside the loop, you can cache it.
If it can change, it should not be cached.
Why would such a construction be needed at all when there is a built-in operator
compactly and idiomatically
for i:= range data {}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question