triple equals vs twice equals
JavaScript performance comparison
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.
| Test | Ops/sec | |
|---|---|---|
3-equals-false |
|
pending… |
2-equals-false |
|
pending… |
3-equals-true |
|
pending… |
2-equals-true |
|
pending… |
2-equals-true-non-coerced |
|
pending… |
2-equals-false-non-coerced |
|
pending… |
3-equals-true-non-coerced |
|
pending… |
3-equals-false-non-coerced |
|
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:
- Revision 1: published by Filip Minev and last updated
- Revision 4: published
- Revision 5: published by ahatchkins
- Revision 6: published
- Revision 7: published
8 comments
That is impressive
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?
@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.
but speed isn't the primary motivation to use
===/!==over==/!=is it? The first pair evaluate totrue/falseif 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.,@doug What?
'' == 0returnstrue, notfalse.@doug You're right that speed shouldn't be the primary motivation to use one over the other. Devs should use the correct operator for the job.
@John-David Dalton thanks for the interesting link.
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]