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

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

问题描述

我经常在函数中使用可选参数,但一些测试表明它们在 Firefox 和 safari 中的性能受到了巨大影响(70-95%).奇怪的是,如果我传入文字值 undefined 则没有惩罚.这里会发生什么?我不会认为这是一个作用域链问题,因为它们本质上是函数的本地问题.我是否开始将 undefined 传递给每个可选参数?

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:http://jsperf.com/function-undefined-args/2

推荐答案

对于这样的函数:

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

就是这样称呼的:

threeArgs(1, 2, 3);

优化器可以自由选择不生成任何代码.它很容易确定没有副作用,因为该函数只是引用其参数值并返回一个简单表达式的结果.由于返回值被忽略,运行时根本没有理由做任何事情.

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.

除此之外,如果代码是:

Beyond that, if the code were:

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

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

the optimizer might decide to generate code roughly equivalent to:

something += 6;

为什么?因为调用是使用数字常量进行的,它可以在代码生成时安全地折叠这些常量.这可能是保守的,因为数字很奇怪,但在这里它们都是整数,所以它可以很好地做到这一点.即使没有,它也可以安全地内联函数:

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.

通过在测试中使用变量而不是常量,并且通过实际使用函数的返回值,您可以混淆"优化器并使其不跳过调用或预先计算结果,但您不能防止它内联.由于这个原因,我仍然认为您的结果很有趣:它揭示了一个事实,即(截至今天)这些优化器对调用函数的方式很敏感.

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天全站免登陆