在JavaScript中与null和undefined进行比较的速度 [英] Speed of comparing to null vs undefined in JavaScript
问题描述
我刚刚运行了一个非常简单的JavaScript 性能测试(不要问为什么)。测试声明了一个变量,但没有为其赋值:
I have just run a very simple JavaScript performance test (don't ask why). The test declares a variable, but doesn't assign anything to it:
var x;
然后将比较值变量的速度与 null
和 undefined $ c进行比较$ c>,换句话说:
It then compares the speed of comparing the value variable to null
, and to undefined
, in other words:
var y =(x == null);
和 var y =(x == undefined);
。
我期待与 undefined
的比较成为禁食。事实上,它远远不够。与 null
的比较是最快的,大约快80%。
I was expecting the comparison with undefined
to be the fasted. In fact it was nowhere near. The comparison with null
was far and away the fastest, around 80% faster.
我描述的结果以上来自于在Chrome中运行测试(版本13)。在Firefox中运行它们会产生更接近我预期的结果(与 undefined
的比较比 null
更快,虽然非常轻微)。
The results I've described above come from running the tests in Chrome (version 13). Running them in Firefox produces results far closer to what I would have expected (the comparison with undefined
is faster than with null
, albeit very marginally).
所以,我的问题是这可能是什么原因?为什么Chrome似乎更喜欢与 null
进行比较呢?
So, my question is what could the cause of this be? Why does Chrome seem to favour the comparison with null
so greatly?
为了快速参考,这里有一个截图结果:
For quick reference, here's a screenshot of the results:
推荐答案
null
是一个无法覆盖的保留关键字,所以当你做的时候与null的比较,您所要做的只是一次比较。
null
is a reserved keyword which cannot be overriden, so when you are doing a comparison against null, all you have to do is a single comparison.
但是,当您检查 undefined
时,引擎必须进行类型查找然后进行比较,这意味着它实际上要求更高一些。
However, when you are checking against undefined
, the engine must do a type lookup and then a comparison, meaning that it is actually slightly more demanding.
如果您需要实际检查某些内容是否未定义,您应该使用
If you need to actually check to see if something is undefined, you should use
if(typeof notSet == "undefined"){ }
证明
尝试...并设置为 null
在您的JavaScript控制台中。
Proof
Try it... and set something to null
in your JavaScript console.
null = "will error";
// Errors with --> ReferenceError: invalid assignment left-hand side
但是,如果你尝试使用undefined,它赢了不对。错误。这并不是说你可以覆盖 undefined
,因为你不能,但是 undefined
是它自己的原语类型。
However, if you try and do it with undefined, it won't error. That is not to say that you can override undefined
, because you can't, but that undefined
is its own primitive type.
null和undefined之间唯一真正的相似之处在于它们都可以被强制转换为布尔值false。
The only real similarity between null and undefined, is that they can both be coerced into a boolean false.
这篇关于在JavaScript中与null和undefined进行比较的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!