Is there a performance benefit on replacing the "==" operator with the "===" operator?

5

I'm using JSLint to check if the JavaScript source code complies with the encoding rules, and it is returning many suggestions for replacing == (two equal signs) with === (three equal signs) when doing things like comparing idlol.value.length == 0 within a if conditional.

Is there a performance benefit in replacing == with === ?

If no type conversion occurs, will there be a performance gain relative to == ?

    
asked by anonymous 09.04.2018 / 02:38

2 answers

7

I did a little test on Node.js v9.8.0:

"use strict";
let t0, t1, dummy;

t0 = (new Date()).getTime();
dummy = true;
for (let i = 0; i < 10000000; ++i) {
    let j = "" + i;
    let k = 0 + i;
    dummy = dummy || (i == k);
}
t1 = (new Date()).getTime();
console.log("" + (t1 - t0) + "ms " + dummy);

t0 = (new Date()).getTime();
dummy = true;
for (let i = 0; i < 10000000; ++i) {
    let j = "" + i;
    let k = 0 + i;
    dummy = dummy || (i === k);
}
t1 = (new Date()).getTime();
console.log("" + (t1 - t0) + "ms " + dummy);

t0 = (new Date()).getTime();
dummy = true;
for (let i = 0; i < 10000000; ++i) {
    let j = "" + i;
    let k = 0 + i;
    dummy = dummy || (i == j);
}
t1 = (new Date()).getTime();
console.log("" + (t1 - t0) + "ms " + dummy);

t0 = (new Date()).getTime();
dummy = true;
for (let i = 0; i < 10000000; ++i) {
    let j = "" + i;
    let k = 0 + i;
    dummy = dummy || (i === j);
}
t1 = (new Date()).getTime();
console.log("" + (t1 - t0) + "ms " + dummy);

The longest time consumed by creating the string j. The results on my machine were as follows:

883ms # int == int verdadeiro
1006ms # int === int verdadeiro
1030ms # int == string verdadeiro
1016ms # int === string falso

Surprisingly, the == operator was faster than ===, but only when the two objects being compared are already of the same type. But it's a minuscule difference (12ns per comparison). The values must be different in a browser or in different versions of Node.js.

    
09.04.2018 / 03:38
3

I believe you are referring to the eqeqeq rule.

The reason for this rule is not due to any performance gain, but rather to improve cohesion, after all Abstract Equality Algorithm is rather obscure, to get an idea, the following comparisons return true :

[] == false
[] == ![]
3 == "03"

In any case, you can create some exceptions for this rule, such as comparisons with null or between literais

smart - literal comparison

/*eslint eqeqeq: ["error", "smart"]*/

typeof foo == 'undefined'
'hello' != 'world'
0 == 0
true == true
foo == null

always, except null - comparison with null

/*eslint eqeqeq: ["error", "always", {"null": "ignore"}]*/

foo == null
    
09.04.2018 / 04:35