R
R
Roman Sarvarov2021-12-21 10:42:41
go
Roman Sarvarov, 2021-12-21 10:42:41

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++ {
    //
}


In the example above, the string "CALL" will be displayed 10 times.

Is it better in Go to put things like this into variables too?

Is this code identical in performance or is the second option preferable?

// 1:
for i := 0; i < len(data); i++ {
    //
}

// 2:
dataLength := len(data)
for i := 0; i < dataLength; i++ {
    //
}


In fact, it seems like I have never seen (even in the official sandbox) that this is transferred to a variable above the loop, len() is cached?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-12-21
@megakor

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.

U
uvelichitel, 2021-12-21
@uvelichitel

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 question

Ask a Question

731 491 924 answers to any question