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.