简体   繁体   中英

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

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?

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.

This 'large' number you are using though, is really large, I bet it's the difference between processing a 32-bit quantity and a more-than-32-bits quantity. Try a base of 1,500,000,00 (sub 32-bit signed), 3,000,000,000 (sub 32-bit unsigned) and 5,000,000,000 (over 32 bit).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM