Why does a function work faster with a complete array than with an empty array?


I have two implements of function, that gets the last element of array.

function first(array) {
  var length = array ? array.length : 0;
  return length ? array[length - 1] : undefined;

function second(array) {
  return array ? array[array.length - 1] : undefined;

And second function work with full array faster than first, but slowly with empty. Why and how I can fix it?

Benchmark with full array: http://jsperf.com/lodash-f-last/

Benchmark with empty array: http://jsperf.com/lodash-f-last/2

If you want your code to be fast you should never ever read out of bounds: V8 deoptimizes the code that does that.

In you second function you do precisely that - you read out of bounds. Instead do the bounds check before reading:

function xlast(array) {
  return (array && array.length > 0) ? array[array.length - 1]
                                     : undefined;