Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do incrementing operators (++) with large numbers have poor performance?

Tags:

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?

like image 358
Malki Avatar asked Oct 25 '15 12:10

Malki


People also ask

Is ++ OK in JavaScript?

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.

What is Preincrement and Postincrement in JavaScript?

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.

What does ++ mean in JavaScript?

The increment operator ( ++ ) increments (adds one to) its operand and returns a value.


1 Answers

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.

like image 132
Benjamin Gruenbaum Avatar answered Oct 18 '22 16:10

Benjamin Gruenbaum