简体   繁体   English

使用函数或类型

[英]Using a function or typeof

How much slower faster is the typeof operator than a function call? typeof运算符比函数调用慢多少? Or is it negligible and micro-optimising? 还是微不足道且微优化?

if (isNumber(myVar)) {
}

if (typeof myVar === 'number') {
}

Or is it negligible and micro-optimising? 还是微不足道且微优化?

Yes, this is definitely something to worry about if and only if you identify the code in question as being a performance bottleneck, which is really unlikely. 是的, 当且仅当您将有问题的代码确定为性能瓶颈时,这才确实值得担心,这确实不太可能。 It's micro-optimization. 这是微观优化。 Function calls are really, really fast even if they don't get optimized out by the JavaScript engine. 即使没有被JavaScript引擎优化函数调用也确实非常快 I used to worry about function call overhead when Array#forEach first appeared on the scene. 我曾经担心Array#forEach首次出现在现场时的函数调用开销。 Even back then , it wasn't an issue, even on the oldest, slowest JavaScript interpreter I could find: The one in IE6. 即使在那时 ,即使在我能找到的最古老,最慢的JavaScript解释器中,这也不是问题:IE6中的那个。 Details on my blog: foreach and runtime cost 我的博客上的详细信息: foreach和运行时成本

Re whether it takes longer... How long is a piece of string? Re是否需要更长的时间...一根线要花多长时间? It totally depends on the JavaScript engine you're using and whether the code in question is identified as a "hot" spot by the engine (assuming it's an engine like V8 that works in stages and optimizes hot spots). 这完全取决于您使用的JavaScript引擎以及该代码是否被引擎识别为“热点”(假设它是像V8这样的引擎,可以分阶段工作并优化热点)。

A modern engine is likely to inline that if it becomes important to do so. 如果很重要,现代引擎很可能会内联。 That is not a guarantee. 那不是保证。

Or is it negligible and micro-optimising? 还是微不足道且微优化?

It's negligible and micro-optimizing. 它可以忽略并且是微优化的。


If you want to check if something's a number, I recommend using an isNaN check and then casting to a number. 如果要检查数字是否为数字,建议使用isNaN检查,然后转换为数字。

if (!isNaN(myVar)) {
  myVar = +myVar;
}

In this way, you don't actually care how the value gets treated as a number. 这样,您实际上并不关心值如何被视为数字。

Someone using the API could then choose to pass an object that can be treated as a number: 然后,使用API​​的人可以选择传递一个可以视为数字的对象:

myVar = {
  valueOf: function () {
    return 5;
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM