简体   繁体   English

将相同的数组/对象元素分配给相同元素的性能

[英]Performance of assigning the same array/object element to the same element

I am curious about the performance of assigning the same element to itself. 我对为其分配相同元素的性能感到好奇。 Is V8 smart enough to understand this should not be executed? V8是否足够聪明,可以理解不应执行此操作?

obj.key = obj.key;

The use case would be something like. 用例将是类似的。

Object.keys(otherObj).forEach(e => {
  if(!obj[e]) {
    obj[e] = foo();
  }
});

If we use a ternary operator instead of if-statement, would there be a penalty performance? 如果我们使用三元运算符代替if语句,会不会有惩罚性能?

Object.keys(otherObj).forEach(e => obj[e] = obj[e] ? obj[e] : foo());

V8 developer here. V8开发人员在这里。 I don't think there's a case where obj[e] = obj[e] assignments will be optimized away. 我不认为obj[e] = obj[e]分配不会被优化。 Deciding that such an optimization would be valid requires so much knowledge about obj and e that checking for all that would in most cases be too expensive to be worth it. 要确定这样的优化是有效的,就需要对obje有足够的了解,以至于在大多数情况下检查所有这些都太昂贵了而不值得。

As Bergi points out, obj[e] = (... ? obj[e] : ...) is conceptually significantly more complicated and therefore even less likely to ever be optimized away, even if you assume that we'll spend a couple more years improving V8. 正如Bergi所指出的, obj[e] = (... ? obj[e] : ...)在概念上要复杂得多,因此即使您假设我们将花费一个再改进V8。

Regarding obj.key vs obj[e] (for both loading and storing), if they both see only one object shape and only one property name, they'll have pretty much the same performance. 关于obj.keyobj[e] (用于加载和存储),如果它们都只看到一个对象形状和一个属性名称,它们的性能几乎相同。 If [e] sees more than one property name (like in your example looping over Object.keys() ), it will be somewhat slower; 如果[e]看到多个属性名(例如在您的示例中循环Object.keys() ),则它会稍微慢一些; however .key isn't really an alternative there -- it's precisely the flexibility of [e] that makes it slower. 但是, .key并不是真正的替代方案-正是[e]的灵活性使其变得更慢。 If either of them sees more than one shape for obj , they'll be slower than otherwise, with [e] taking a bigger hit than .key ; 如果它们中的任何一个看到obj形状都不止一个,则它们的速度将比其他方法慢,并且[e]的命中率要比.key this will eg be the case when your loop ends up adding properties that weren't there before. 例如,当您的循环最终添加以前不存在的属性时,就是这种情况。

All that said, any performance differences are probably too small to matter, and my recommendation is to write the code that's most readable -- or run your own measurements to figure out with certainty whether there's a measurable difference in your case. 综上所述,任何性能差异可能都太小了,我的建议是编写可读性最强的代码-或运行自己的测量以确定您的情况是否存在可测量的差异。 Keep in mind that microbenchmarks are often misleading; 请记住,微基准测试经常会产生误导; use an app that comes as close as possible to your production environment for such tests. 使用与您的生产环境尽可能接近的应用程序进行此类测试。

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

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