0

I read the following from w3schools here

Bad Code:
for (i = 0; i < arr.length; i++) {

Better Code:
l = arr.length;
for (i = 0; i < l; i++) {

I was taught C++ and Java in school and I never learnt that this is something we need to consider for efficiency. Isn't getting the size of array just a O(1) operation? Is this optimization really necessary and is it really what people do in industry?

EDIT:

Given that the array's size won't change.

4
  • In the old days it mattered, in current JS engines it makes no difference. Commented Oct 7, 2015 at 21:39
  • It's a micro-optimization -- in the first instance, arr.length must be recalculated each time you pass through the loop. For small loops, it's completely unnoticeable. Commented Oct 7, 2015 at 21:39
  • @0x499602D2 please elaborate - if anything it's more useful in JS than in other languages Commented Oct 7, 2015 at 21:39
  • @Alnitak I agreed right after you mentioned the array length could change. Commented Oct 7, 2015 at 21:39

1 Answer 1

4

Yes, getting the length is O(1), but it's not typically optimised out because it's feasible for the array length to change during the loop.

In the case where I know the array length won't change my preferred syntax is:

for (var i = 0, n = arr.length; i < n; ++i) 

As usual, w3schools misses the point - the first version they quote isn't always bad code, because that code might be exactly what's required if the array length is modified during the loop.

Sign up to request clarification or add additional context in comments.

6 Comments

It's also better habit to write the loop in the manner. Not all stopping conditions are going to be trivial to calculate.
So even if I know the size of array won't change, I should not call arr.length every time?
@Arch1tect it might make a tiny bit of difference to performance, but why evaluate a loop invariant for every pass of the loop if you don't have to?
I agree it's slightly faster, I just feel that it's such tiny improvement that I shouldn't need to change the way I used to write for loops..
so don't - but in any event it's always better to move any loop invariants outside of the loop.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.