Be consistent in use of Numbers
suggest changeIf the engine can predict that every Number in a hot loop is a small integer, it can use a faster internal representation. BigInt is a separate type and is not part of this optimization. The timings below are one Node.js run, not a guarantee.
process.hrtime exists only in Node.js. arr is the array created in the next snippet:
const sum = (function (arr) {
const start = process.hrtime();
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
const diffSum = process.hrtime(start);
console.log(`Summing took ${diffSum[0] * 1e9 + diffSum[1]} nanoseconds`);
return sum;
})(arr);
Let’s make an array and sum the elements:
const N = 12345;
const arr = [];
for (let i = 0; i < N; i++) arr[i] = Math.random();
Example result:
Summing took 384416 nanoseconds
Now, let’s do the same but with only integers:
const N = 12345;
const arr = [];
for (let i = 0; i < N; i++) arr[i] = Math.round(1000 * Math.random());
Example result:
Summing took 180520 nanoseconds
Summing integers took half the time here.
Engines do not use only the types you see in JavaScript. Every Number is an IEEE 754 double-precision floating-point value; the language has no separate integer type. When an engine can prove that a value stays a small integer, it can store it in a more compact form, such as a 31-bit signed integer (a “SMI” in V8).
This kind of optimization is especially important for computation or data intensive applications.