Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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;
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!