triple equals vs twice equals

JavaScript performance comparison

Test case created by Filip Minev and last updated

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var testStr = 'test';
    var testInt = 111;
    var testIntSame = 111;
    var testIntDiff = 112;
    var testIntStr = '111';
    var result;
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
3-equals-false
result = (testStr === testInt);
pending…
2-equals-false
result = (testStr == testInt);
pending…
3-equals-true
result = (testIntStr === testInt);
pending…
2-equals-true
result = (testIntStr == testInt);
pending…
2-equals-true-non-coerced
result = (testIntSame == testInt);
pending…
2-equals-false-non-coerced
result = (testIntDiff == testInt);
pending…
3-equals-true-non-coerced
result = (testIntSame === testInt);
pending…
3-equals-false-non-coerced
result = (testIntDiff === testInt);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

8 comments

Colum commented :

That is impressive

thinkt4nk commented :

so if the type actually has to be coerced, then it's much slower, but if the types are the same, then two-equals is much faster?

John-David Dalton commented :

@thinkt4nk By spec both == and === execute the same number of steps when comparing values of the same type.

Browser's JS engines may optimize for one or the other in different situations but it really doesn't matter as these are both millions and millions of ops/sec and won't make a perf difference in real world use.

doug commented :

but speed isn't the primary motivation to use ===/!== over ==/!= is it? The first pair evaluate to true/false if the two operands are of the same type and have the same value. On the other hand the latter pair, will attempt coercion if the two operands are of different type. The set of rules used for this attempted coercion was likely borrowed from a Soviet tractor factory – e.g.,

'' == 0    // false
0 == ''    // true

Mathias Bynens commented :

@doug What? '' == 0 returns true, not false.

Filip Minev (revision owner) commented :

@John-David Dalton thanks for the interesting link.

doug commented :

Thanks for pointing out the typo Mathias--left off the quotes when I copied it from my interpreter--should read:

'' == '0'

[original post above incorrectly recites: '' == 0]

Add a comment