In the following code:
for (var i = 0; i < object.length; i++){
....
}
does the operation object.length
get evaluated every time in the iteration?
It would make most sense that the language will evaluate this once and save the result. However, I was reading some code where someone evaluated the operation before the loop started and stored it in a variable that was used in the end-condition.
Do different languages handle this differently? Any specific info for Javascript?
Syntax. The for loop consists of three optional expressions, followed by a code block: initialization - This expression runs before the execution of the first loop, and is usually used to create a counter. condition - This expression is checked each time before the loop runs.
The initialization is an expression that initializes the loop — it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. When the expression evaluates to false , the loop terminates.
The repeat / until loop is a loop that executes a block of statements repeatedly, until a given condition evaluates to true . The condition will be re-evaluated at the end of each iteration of the loop, allowing code inside the loop to affect the condition in order to terminate it.
The purpose the break statement is to break out of a loop early. For example if the following code asks a use input a integer number x. If x is divisible by 5, the break statement is executed and this causes the exit from the loop.
It obviously depends on the language. For JavaScript, the spec (ECMAScript §12.6.3) requires it always be evaluated each time. As an optimization, a specific JavaScript runtime could skip one or more of the length calls, if it could prove that the result would not change.
Completely depends on the language and (possibly) on what's in the loop. The compiler/interpreter may or may not be able to determine with certainty that the "length" property won't be changed by something in the loop.
In Javascript, it's a safe bet that it'll be re-evaluated. A simple property reference like that probably isn't that bad, but something like a function call could be a performance problem. edit To clarify, by "a function call" I mean code of any form that computes the loop termination condition in any way expensive enough to make you feel bad about doing it on each iteration.
Thus (pardon my jQuery),
for (var i = 0; i < $('.foo').length; ++i) { /* ... */ }
would involve a traversal of the whole DOM on each iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With