Skip to content
Advertisement

In Javascript, why is ‘while(true’ slower than ‘for(…)’ when they are both iterating the same number of times?

Assuming that the while(true) will break at the same time as the for(...) loop, why is the for(...) faster?

According to jsbench, it is about 7% slower to use the while(true)

Here’s the code I’ve used in the jsbench:

Using a while(true) loop

/* generate array */
const arr = []
for(let i = 0; i < 1000; i++){
    arr.push(i)
}

let i = 0
while(true){
    if(arr[i] >= 900){
        return;
        
    }
    i++
}

using a for(...) loop:

/* generate array */
const arr = []
for(let i = 0; i < 1000; i++){
    arr.push(i)
}

for(let i = 0; i < arr.length; i++){
    if(arr[i] >= 900){
        return;
    }
}

Advertisement

Answer

The timing has to do with both your code and how JavaScript is compiled. The differences are pretty inconsequential in this example though, so testing which is faster varies each time the code is run and the results are pretty indeterministic. Generally, they should take about the same time or ever so slightly faster or slower.

Your code

Your while loop will continue simply because you have the condition set to always be true. You didn’t include a condition to check if it should stop at any point after each iteration is complete.

Your for loop on the other hand has a condition that is checked every single time an iteration is complete (checking if i < arr.length still).

Other than that, your code is pretty much the same. They both have the same block of code, the difference is that the while loop increments i inside its code block, rather than like the for loop that increments i after its inner code block.

The differences in this case are pretty inconsequential.

Compilation

If you’ve ever studied some assembly code, you should be a little familiar with some of the structures for loops.

Depending on how the code is compiled determines which operations/instructions are run in what order. Also, the structure for a while loop should usually be different from a for loop in assembly, meaning that there may be an extra instruction to run in a for loop versus a while loop or vice versa depending on the programming language.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement