I noticed that when incrementing a counter, it is significantly slower when the value of the counter is a large number. I tried it in Chrome, Firefox, and IE11, all show worse performance in large numbers.
See jsperf test here (code below):
var count1 = 0;
var count2 = new Date().getTime();
var count3 = 1e5;
var count4 = 1e9;
var count5 = 1e12;
var count6 = 1e15;
function getNum1() {
return ++count1;
}
function getNum2() {
return ++count2;
}
function getNum3() {
return ++count3;
}
function getNum4() {
return ++count4;
}
function getNum5() {
return ++count5;
}
function getNum6() {
return ++count6;
}
Why does it happen?
The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces.
JavaScript Increment operator (++ )In the first case (i.e. post-increment) the operator increases the variable var1 by 1 but returns the value before incrementing. In the second case (i.e. pre-increment) the operator increases the variable var1 by 1 but returns the value after incrementing.
The increment operator ( ++ ) increments (adds one to) its operand and returns a value.
Modern JavaScript runtimes and compilers perform an optimization called SMI (Small Integers).
All numbers in JavaScript are double precision floating points which are relatively slow to perform calculations on. However, in practice in a lot of cases (for example the majority of for
loops) we're working with integers.
So - it is very useful to optimize numbers to perform efficient calculations when possible. When the engine can prove that a number is a small integer - it will gladly treat it as such and perform all calculations as if the number is an integer.
Incrementing a 32-bit integer is a single processor operation and is very cheap. So you get better performance doing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With