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];
};
Richard
  • 4,809
  • 3
  • 27
  • 46
  • I _think_ it is unlikely that this alone cripples your performance. You should describe what your animation does and how and when it runs. Finally it is generally frowned upon to extend the prototype of native types. – customcommander Jan 03 '20 at 15:50

1 Answers1

2

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.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153