Home > Blockchain >  Why is declaring a variable outside of the loop more faster?
Why is declaring a variable outside of the loop more faster?

Time:05-05

A few weeks ago, I heard that declaring the true/false condition variable outside of the loop was faster. So, I wanted to try it out.


So, basically, I made this code to see which is faster.

These are the two loops.

// Initialization
const arr = [1, 2, 3, 4, 5];

// Bad Loop
console.time("bad");

for (let i = 0; i < arr.length; i  ) {
  console.log(arr[i]);
}

console.timeEnd("bad");

// Good Loop
console.time("good");

let l = arr.length;
for (let i = 0; i < l; i  ) {
  console.log(arr[i]);
}

console.timeEnd("good");

When the code is run, there is a significant difference in the time it takes to run the bad loop, versus the time it takes in the good loop. (No matter how quick the bad loop is, the good loop is always quicker.)


So, my question is why is this happening? The only difference between the two loops is the fact that the good loop defines the array length before the loop begins, while the bad loop gets it in the loop.

CodePudding user response:

Basically, this is why the code in the bad loop is slower than the good loop.


1. Why is the bad loop slow?

First, let's take a look at the bad loop.

const arr = [1, 2, 3, 4, 5];

console.time("Bad");

for (let i = 0; i < arr.length; i  ) {
  console.log(arr[i]);
}

console.timeEnd("Bad");

The thing that is making this loop slow is the fact that it accesses the length property for every iteration.

This can drastically decrease performance, as for five times (in this case), it has to access a property.

As you can see, it is no surprise that the bad loop is slower.


2. Why is the good loop so fast?

Take a look at the good loop:

const arr = [1, 2, 3, 4, 5];

console.time("Good");

let l = arr.length;
for (let i = 0; i < l; i  ) {
  console.log(arr[i]);
}

console.timeEnd("Good");

You can see that the reason it is faster is because it accesses the length outside of the loop. In other words, it only accesses the length once, compared to the bad code, which accesses it five times.

You can see that by defining the variable, it reduces the time taken to get the length property from the away, thus, increasing performance!


In conclusion, the good loop is faster as it only has to access the length property once!

  • Related