I was asked to print numbers from 100 to 1 in a for
loop with the index starting from 1. I came up with this solution:
var a = [];
for(var i = 1; i <= 100; i++) {
a.push(i);
}
console.log(a.reverse());
I was thinking of a better way of doing this after the interview and came up with this
for(var i = 1; i <= 100; i++) {
console.log((100-i)+1);
}
Now what blows my mind is, jsperf.com's test indicates the former is faster. How is this even possible? Creating an array, pushing something into it and reversing it before printing definitely seems slower than simple arithmetic. Could anyone help me understand this?
3 Answers 3
It turns out accessing console take's more time than pushing a value in an array.
Console.log is indeed implemented as a synchronous function (next print starts only after last print finishes).
Meaning, there is no buffering system. The program goes to blocking state until console.log() finish printing, everytime.
Performance difference in above two cases is due to the difference in the number of console.log() call.
-
1\$\begingroup\$ The test results are meaningless, the error on 4 samples ranges 2 orders of magnitude. That is statistically called noise. You need to test 1000+ samples, 1000+ times, include the error bars. Then you can make a deduction about performance, use that to make a prediction, and only when you confirm your prediction via experiment are you able to make a meaningful statement about performance. \$\endgroup\$Blindman67– Blindman672018年02月10日 05:51:10 +00:00Commented Feb 10, 2018 at 5:51
-
\$\begingroup\$ Thank you, sir. Though I am not predicting anything, It was only for demonstration. \$\endgroup\$snehm– snehm2018年02月10日 10:07:46 +00:00Commented Feb 10, 2018 at 10:07
You can also push the reversed order of values in the array so you can avoid reverse() and can call console.log() outside the loop.
var a = [];
for(var i = 1; i <= 100; i++) {
a.push(101-i);
}
console.log(a)
Both variants presented look somewhat indirect. What about
for (var i = 100 ; 1 <= i ; --i)
console.log(i);
(I grant that print numbers from 100 to 1 in a for loop with the index starting from 1
reads use an array - not sure about starting from 1.)
for (var index = 1 ; 1 <= (99+index) ; --index)
console.log(99+index);
-
\$\begingroup\$ Personally preferring
for (var i = 101 ; 0 < --i ; )
. \$\endgroup\$greybeard– greybeard2018年02月10日 09:28:12 +00:00Commented Feb 10, 2018 at 9:28
Explore related questions
See similar questions with these tags.
console.log()
. Try timing building the output as a single string, and logging that. \$\endgroup\$