Be consistent in use of Numbers

suggest change

If the engine is able to correctly predict you’re using a specific small type for your values, it will be able to optimize the executed code.

In this example, we’ll use this trivial function summing the elements of an array and outputting the time it took:

// summing properties
var sum = (function(arr){
        var start = process.hrtime();
        var sum = 0;
        for (var i=0; i<arr.length; i++) {
                sum += arr[i];
        }
        var 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:

var     N = 12345,
        arr = [];
for (var i=0; i<N; i++) arr[i] = Math.random();

Result:

Summing took 384416 nanoseconds

Now, let’s do the same but with only integers:

var     N = 12345,
        arr = [];
for (var i=0; i<N; i++) arr[i] = Math.round(1000*Math.random());

Result:

Summing took 180520 nanoseconds

Summing integers took half the time here.

Engines don’t use the same types you have in JavaScript. As you probably know, all numbers in JavaScript are IEEE754 double precision floating point numbers, there’s no specific available representation for integers. But engines, when they can predict you only use integers, can use a more compact and faster to use representation, for example, short integers.

This kind of optimization is especially important for computation or data intensive applications.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Performance Tips:
* Be consistent in use of Numbers

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
58 Performance Tips
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde