性能损失不确定的参数 [英] Performance penalty for undefined arguments

查看:122
本文介绍了性能损失不确定的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在功能可选参数,但一些测试表明,它在Firefox和Safari(70-95%),他们的一个巨大的性能损失。奇怪的是,如果我通过在该数值中的未定义的则没有处罚。什么可能会发生在这里?我不会认为这是一个作用域链问题,因为它们本质上是局部的功能。我是不是要开始传递的未定义的到每一个可选的参数?

I quite often have optional arguments in functions, but some testing is showing a huge performance hit for them in firefox and safari (70-95%). Strangely, if I pass in the literal value undefined then there is no penalty. What could be happening here? I wouldn't have thought that it was a scope chain issue as they are inherently local to the function. Am I to start passing undefined into every optional argument?

jsPerf:<一href=\"http://jsperf.com/function-undefined-args/2\">http://jsperf.com/function-undefined-args/2

推荐答案

有关这样的功能:

function threeArgs(x, y, z) {
  return x + y + z;
}

这就是所谓的像这样的:

that's called like this:

threeArgs(1, 2, 3);

优化是自由做出的选择不产生code在所有。它很容易为​​它确定有没有副作用,因为函数只是引用它的参数值,并返回一个简单的前pression的结果。由于返回值被忽略,没有理由为运行在所有做任何事情。

the optimizer is free to make the choice to generate no code at all. It's fairly easy for it to determine that there are no side effects, because the function simply references its parameter values and returns the result of a simple expression. Since the return value is ignored, there's no reason for the runtime to do anything at all.

除此之外,如果code组:

Beyond that, if the code were:

something += threeArgs(1, 2, 3);

优化器可能会决定产生code大致相当于:

the optimizer might decide to generate code roughly equivalent to:

something += 6;

为什么呢?因为调用与数字常量制成,它可以安全地折叠那些code生成时间。这可能是上保守,因为数字是不可思议,但在这里,他们都是整数,因此很可能做到这一点。即使没有,它可以安全地内联函数:

Why? Because the call was made with numeric constants, and it can safely fold those at code generation time. It might be conservative on that, because numbers are weird, but here they're all integers so it could well do this. Even if it didn't, it could safely inline the function:

something += 1 + 2 + 3;

当有一个参数丢失,但是,它可能是优化舀出和产生一个真正的函数调用。对于这样一个简单的函数,该函数调用的开销很容易解释的性能差异较大。

When there's a parameter missing, however, it may be that the optimizers bail out and generate a real function call. For such a simple function, the overhead of the function call could easily account for a large difference in performance.

通过使用变量而不是常量在测试和实际使用函数的返回值,你可以在迷惑了优化,并保持它跳过来电或pre计算的结果,但你不能从内联继续使用它。我仍然认为,你的结果是这个原因有趣:它暴露的事实(截至今天无论如何)的优化是该函数被调用的方式敏感

By using variables instead of constants in a test, and by actually using the return value of the function, you can "confuse" the optimizer and keep it from skipping the call or pre-computing the result, but you can't keep it from inlining. I still think that your result is interesting for that reason: it exposes the fact that (as of today anyway) those optimizers are sensitive to the way that functions are invoked.

这篇关于性能损失不确定的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆