Adding a function to the array prototype

huangapple go评论68阅读模式
英文:

Adding a function to the array prototype

问题

Adding this simple JavaScript function to the array prototype causes a significant slowdown in my animations? NB To draw a single frame does use a lot of arrays. Is adding your own functions to the Array prototype that significant? Array.prototype.last = function() { return this[this.length - 1]; };

英文:

Why does adding this simple JavaScript function to the array prototype cause a significant slowdown in my animations?

NB To draw a single frame does use a lot of arrays. Is adding your own functions to the Array prototype that significant?

Array.prototype.last = function()
{
    return this[this.length - 1];
};

答案1

得分: 2

以下是翻译好的部分:

这个答案假设代码已经进行了性能分析并确定了瓶颈所在。如果不是这种情况,请首先进行性能分析:Chrome | Firefox | Edge

以下的建议侧重于V8特定的优化,但通常也会提高其他引擎的性能。


虽然在功能上是等效的,但我建议对last()进行两个更改:

  • 它应该是一个接受数组作为参数的静态方法,而不是Array的成员方法。
  • 它应该避免越界访问

有了这个想法,试试这个:

function last (array) {
  var lastIndex = array.length - 1;
  if (lastIndex === -1) return undefined;
  return array[lastIndex];
}

在这一点上,你可能会想

> 很酷,现在我可以将这个用于类似数组的对象,比如arguments

如果你避免了通用的用法,那么该函数可以保持优化,否则优化器必须退出并使用效率较低的抽象以允许除Array以外的类型作为输入。

英文:

This answer assumes that the code has been profiled and the bottleneck identified here. If this is not the case, please do that first: Chrome | Firefox | Edge

The tips below focus on V8-specific optimization, but typically improve performance on other engines as well.


While functionally equivalent, I'd suggest making two changes to last():

  • It should be a static method accepting an array as a parameter, not a member method of Array.
  • It should avoid out-of-bounds access.

With that in mind, try this:

function last (array) {
  var lastIndex = array.length - 1;
  if (lastIndex === -1) return undefined;
  return array[lastIndex];
}

At this point, you might be thinking

> Cool, now I can re-use this for array-like objects such as arguments.

If you avoid generic usage, then the function can stay optimized, otherwise the optimizer has to bail out and use less efficient abstractions in order to allow types other than Array as input.

huangapple
  • 本文由 发表于 2020年1月3日 23:47:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定