为什么将这个简单的 JavaScript 函数添加到数组原型(prototype)会导致我的动画速度明显变慢?
NB 绘制单个帧确实使用了很多数组。将您自己的函数添加到 Array 原型(prototype)是否重要?
Array.prototype.last = function()
{
return this[this.length - 1];
};
最佳答案
这个答案假设代码已经被分析并且瓶颈在这里被识别。如果不是这种情况,请先执行此操作:Chrome | Firefox | Edge
下面的技巧着重于 V8 特定的优化,但通常也会提高其他引擎的性能。
虽然功能相同,但我建议对 last()
进行两处更改:
- 应该是接受数组作为参数的静态方法,而不是
Array
的成员方法。 - 应该avoid out-of-bounds access .
考虑到这一点,试试这个:
function last (array) {
var lastIndex = array.length - 1;
if (lastIndex === -1) return undefined;
return array[lastIndex];
}
此时,你可能会想
Cool, now I can re-use this for array-like objects such as
arguments
.
如果你avoid generic usage ,那么函数可以保持优化,否则优化器必须退出并使用效率较低的抽象,以允许 Array
以外的类型作为输入。
关于javascript - 向数组原型(prototype)添加一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59581440/