How a single line code change, improved my performance

mrh0200

MR.H

Posted on February 26, 2023

How a single line code change, improved my performance

I was experimenting with javascript for a project i was working on. I tried to log 0 to 1 Million in console because, why not?

I ran the below code

console.time('time')
for (let i=0;i<=1000000;i++){
console.log(i)
}
console.timeEnd('time')
Enter fullscreen mode Exit fullscreen mode

The above code will run from 0 to 1M and print's time taken to complete. You can see the output for the above code

0
1
2
...
...
...
999998
999999
1000000
time: 22588.629150390625 ms
Enter fullscreen mode Exit fullscreen mode

You can see the above code ran for about ~22,588 milliseconds.
I tried running the same code multiple time and got an average of ~22,600 ms.

Instead of logging inside the loop I tried to move the log outside of the loop by concatenating numbers to a string

console.time('time')
let output = ''

for (let i=0;i<=1000000;i++){
    output+=`${i}\n`
}

console.log(output)
console.timeEnd('time')
Enter fullscreen mode Exit fullscreen mode
0
1
2
...
...
...
999998
999999
1000000
time: 286.9052734375 ms
Enter fullscreen mode Exit fullscreen mode

As you can see above code ran 200% faster then previous code

The reason, is that the first code logs each number to the console immediately as it is generated by the loop. This means that the console has to keep up with the loop and display each number as it is generated. This can be slow, especially when dealing with a large number of iterations.

On the other hand, the second code uses a string to store all the numbers and newline characters, and then logs them in a single string. This approach is faster because it avoids the overhead of logging each number to the console separately.

In general, it's a good practice to avoid logging large amounts of output to the console, especially when dealing with large data sets. Instead, you can store the data in a data structure (like an array) and then process it later, or write it to a file for further analysis. This can help improve performance and avoid unnecessary overhead.


Thanks for reading, Please leave a like and share your thoughts in the comment section

Happy coding

💖 💪 🙅 🚩
mrh0200
MR.H

Posted on February 26, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Common Git Commands and what they do
beginners Common Git Commands and what they do

January 24, 2023

Getting Started with TailwindCSS
beginners Getting Started with TailwindCSS

January 23, 2022

JavaScript Bites: Closure
beginners JavaScript Bites: Closure

November 16, 2021