DEV Community

MR.H
MR.H

Posted on

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

Top comments (16)

Collapse
 
bugb profile image
bugb • Edited

Quoted from Steve Baker

The thing is that beginners in programming often kinda imagine that the amount of time something takes depends (more or less) on how many lines of code there are executed…which is very much not the case.

On a modern computer, is print statement will usually result in…

  1. Calling a library function. Which may have to do things like turning a number into a string of digits in hex or decimal - or into a scientific notation or something…resulting in a new string.
  2. The characters in the string being copied into a buffer.
  3. The buffered string being passed to some operating system function. Which will find the device driver for the “virtual teletype” device which will pass it on to the windowing system…possibly requiring your program to be paused while the windowing system does it’s work.
  4. The windowing system now has to decide whether your text is visible on-screen or hidden behind another window…and whether it causes your window to scroll or something.
  5. Then the string has to be turned into graphics commands that are sent to the GPU, which has to turn them into pixels on the screen. The GPU might be busy doing something else - so your graphics commands may be queued up behind other commands… And on and on. Each of those steps could easily be hundreds - maybe even thousands of lines of code.

So - yeah - print statements are very often the slowest thing in your entire program - and in many cases, a single print statement can take more time than the rest of your ENTIRE program.

Worse still - because it MIGHT cause the operating system to stall your entire program - or it MIGHT just append your string into an existing buffer and return - they are wildly unpredictable. Your program might print one character a thousand times - and the first 999 times, the process is relatively fast - and then the 1000th time - your program is stalled for half a second.

source: quora.com/Do-print-statements-in-t...

Collapse
 
rc2168st profile image
rc2168st • Edited

this one is more optimized, will give you 10-20% faster response.

console.time('abc')
let output = []

for (let i=0;i<=10000000;i++){
    output.push(i)
}

console.log(output.join('\n'))
console.timeEnd('abc')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mrh0200 profile image
MR.H

HI @rc2168st

tried your code

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

for (let i=0;i<=10000000;i++){
    output.push(i)
}
console.timeLog('time')
console.log(output.join('\n'))
console.timeEnd('time')
Enter fullscreen mode Exit fullscreen mode

Output

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

Even the loop completed in 109 ms it took another 2800 ms for the join statement to get completed

Collapse
 
rc2168st profile image
rc2168st

& i don't think it took 3 seconds. On my machine this approach was faster then yours.

Collapse
 
rc2168st profile image
rc2168st

Set the timer for “join” separately & for console.log separately

Collapse
 
rc2168st profile image
rc2168st

Do both approach test in a single script not separate.

Collapse
 
roboxgamer profile image
RoboXGamer

yes this code is more bad!

Collapse
 
hoargarth profile image
Alex Berger

I know this article is about moving the console.log out of the loop.

But ... 😎

console.time('time');

console.log(Array(1000001).keys().join('\n'));

console.timeEnd('time')
Enter fullscreen mode Exit fullscreen mode

~200ms
Aaaand we are ending up with a whopping 6.9MB of string 🤣

Collapse
 
wadecodez profile image
Wade Zimmerman

and now you have a memory problem. when working with large data in the real world it's better to work in chunks. so instead of logging everything at once you would build up a buffer/queue then empty the buffer/dequeue at an arbitrary interval usually in a background task.

The problem with big data is it's always there. It doesn't really matter how you restructure the problem it's going to cause headache somewhere.

Collapse
 
makisce profile image
MakisCE

storing in an array and "printing" every xxxxx numbers seems to work even faster indeed

console.time('time')
let output = []
for (let i=0; i<=1000000; i++){
    output.push(i)
    if (i % 10000 == 0) {
        console.log(output.join('\n'))
        output = []
    }
}
console.log(output.join('\n'))
console.timeEnd('time')
Enter fullscreen mode Exit fullscreen mode

comparing "string build", "array" and "array and flush every xxx"
jsben.ch/rBvkT

Collapse
 
ant_f_dev profile image
Anthony Fung

Interesting to see such a time difference.

Was this a purely theoretical experiment? Generally, I would only leave console.log in the code for debugging purposes, for which it doesn't matter that much if it's slower. Once everything is working, there usually isn't any reason to log to the console.

Collapse
 
sathiraguruge profile image
Sathira Guruge

Agree, we should only use console.log only for development/debugging purposes. Even if its a backend or frontend application you should not use it. Instead we can use a logger like raven to catch errrors.

But this is a fun experiment. The first option took time time because an I/O operation was involved in each iteration.
1.Read the value from variable i
2.Print it

Collapse
 
mrh0200 profile image
MR.H

Yes, it was an experimental run, I was testing the time taken to run loops and found this

Collapse
 
floriannicolas profile image
Florian Nicolas

Hi, nice article. I tried it and I seems to have better results with this code, which is pretty close to @rc2168st answer :

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


for (let i=-1;i<=1000000;++i){
    output[i] = i
}

console.log(output.join('\n'))
console.timeEnd('time')
Enter fullscreen mode Exit fullscreen mode
  • For me, output[I] = i has always been more improved than output.push(i)
  • Same for ++I vs I++ especially in the case of very large loops like here

But in reality it seems to depend on browser :
I made a simple benchmark jsbench.me/38leqsrqbt/2
And my solution seems to be faster in Firefox and Safari, but not in Chrome.

Collapse
 
tallberg profile image
tallberg

Use Output = new Array(1000000) to speed it up a bit more.

Collapse
 
grzesiekds profile image
grzesiek-ds

In most languages, signaling something to user by using text or visual interface, is quite heavy operation, because (as mentioned in previous comment) theres a lot of stuff which just have to happen.

In first case, calling console.log is the heavy part, but in second, its printing the string, because its so big.
Try to measure only console.log performance, and log string with different length, You will see the differences aswell.

Also, have a look at performance API, its more precise than console.
developer.mozilla.org/en-US/docs/W...