lodash.last vs [].slice.call

Benchmark created by Mai Chân Chính on


Preparation HTML

<script src='https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js'></script>
<script>
Array.from = function from (target, mapfn, thisArg) {
    var result = [],
        mapping = typeof mapfn === 'function',
        iterator = thisArg == undefined ? mapfn : function (elem) {
          return mapfn.call(thisArg, elem)
        }

    for (var i = 0, len = target.length; i < len; i++) {
      if (!mapping || iterator(target[i]) === true) {
        result[i] = target[i]
      }
    }

    return result
  }
</script>

Setup

var sliceCall = function() {
    return [].slice.call(arguments, 1)
  }
  
  var fromSlice = function() {
    Array.from(arguments).slice(1)
  }
  
  function slicer (arrayLike, startPos, endPos) {
    if (!arrayLike) {
      return []
    }
    
    var result = [],
        i = typeof startPos === 'number' || startPos instanceof Number ? startPos : 0,
        len = typeof endPos === 'number' || endPos instanceof Number ? endPos : arrayLike.length
    
    if (i < 0) {
      i = i + len
      
      if (i < 0) {
        i = 0
      }
    }
    
    if (len < 0) {
      len = len + arrayLike.length
      
      if (len < 0) {
        len = 0
      }
    }
        
    for (; i < len; i++) {
      result[result.length] = arrayLike[i]
    }
    
    return result
  }
  
  var slicerCall = function() {
    return slicer(arguments, 1)
  }
  
  var lodashLast = function() {
    return _.last(arguments, arguments.length - 1)
  }

Test runner

Ready to run.

Testing in
TestOps/sec
lodash.last
lodashLast(1, 2, 3)
ready
[].slice.call
sliceCall(1, 2, 3)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Mai Chân Chính on