DEV Community

Farhan Yahya
Farhan Yahya

Posted on • Updated on

Did you nest your loop perfectly? Let's check it out.

Have you ever taught of how loops hurt the execution time of your code? if not then I think you should begin to worry about all these petty stuff when writing programs.

Let's see how we can make your loop better. Let's say we have an array A of size 9 and an array B of size 7, and our goal is to find the total sum when every single element in A is multiplied to every single element in B. Our code will be like below.

let a = [1,2,3,4,5,6,7,8,9];
let b = [1,2,3,4,5,6,7];

let sum = 0;

for(let i = 0;i<a.length;i++){ //looping 9 elements
    for(let j = 0;j<b.length;j++){ //looping 7 elements
        sum += a[i]*b[j];
    }
}
console.log(sum);

Wait, let's analyze this loop. Let's assume that a single iteration takes a second. Then that means that the outer loop which loops through array A(9 elements) will take 9s to run and the inner loop that loops through array B will take 7s to run. But because the inner loop is inside another loop, and the inner loop is called 9 times, the whole code will then take 9+(9x7) seconds to run. Meaning it takes our code 72s(1m 12s) to run.

How do we reduce the execution time?

As simple as it is, let's just make sure to always nest the loop that iterates the most. In the example above, instead of nesting the loop that goes through B, we would rather nest the loop that goes through A.

let a = [1,2,3,4,5,6,7,8,9];
let b = [1,2,3,4,5,6,7];

let sum = 0;

for(let i = 0;i<b.length;i++){ // looping 7 elements
    for(let j = 0;j<a.length;j++){ //looping 9 elements
        sum += b[i]*a[j];
    }
}
console.log(sum);

Then, our total time taken instead of being 9+(9x7) seconds will be 7+(7x9) seconds which is 70s(1m 10s).

Hence time saved is 72s - 70s which is 2s. Imagine the time saved in computations with large array sizes. Hope you liked it

Top comments (1)

Collapse
 
jotafeldmann profile image
Jota Feldmann

Hi Farhan, please, can you explain the origin of the "9" before the plus sign?

Original: 9+(9x7)

In my mind is just 9x7 or 7x9, which is the same :)

Thanks.