Function.prototype.bind vs Polyfill

JavaScript performance comparison

Revision 5 of this test case created by Fishrock123

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  // Adapted for jsperf from
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  function bind(target, thisArg) {
      var i = arguments.length - 1, boundArgs = [];
      if (i > 0)
      {
          boundArgs.length = i;
          while (i--) boundArgs[i] = arguments[i + 1];
      }
  
      if (typeof target !== 'function') throw new TypeError();
  
      function bound() {
          var i = arguments.length, args = new Array(i);
          while (i--) args[i] = arguments[i];
          args = boundArgs.concat(args);
          target.apply(this instanceof bound ? this : thisArg, args);
      }
  
      bound.prototype = (function F(proto) {
          if (proto) F.prototype = proto;
          if (!(this instanceof F)) return new F();
      })(target.prototype);
  
      return bound;
  }
  
  function old_polyfill_bind(fn, oThis /* , ...aArgs */ ) {
    if (typeof fn !== "function") {
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }
  
    var aArgs = Array.prototype.slice.call(arguments, 2);
    var fToBind = fn;
    var fNOP = function() {};
    var fBound = function _() {
      var scope = this instanceof fNOP && oThis ? this : oThis;
      var args = aArgs.concat(Array.prototype.slice.call(arguments));
      return fToBind.apply(scope, args);
    };
  
    fNOP.prototype = fn.prototype;
    fBound.prototype = new fNOP();
  
    return fBound;
  }
  
  
  function callback() {}
  
  var scope = {
    x: 3
  };
  var nativeBound = callback.bind(scope);
  var customBound = bind(callback, scope);
  var oldCustomBound = old_polyfill_bind(callback, scope);
  var nativeBoundArgs = callback.bind(scope, "foo", "bar");
  var customBoundArgs = bind(callback, scope, "foo", "bar");
  var oldCustomBoundArgs = old_polyfill_bind(callback, scope, "foo", "bar");

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Old Polyfill bind
oldCustomBoundArgs();
pending…
Optimized Polyfill bind (with arguments)
customBoundArgs();
pending…
Native bind
nativeBound();
pending…
Optimized Polyfill bind
customBound();
pending…
Old Polyfill bind
oldCustomBound();
pending…
Native bind (with arguments)
nativeBoundArgs();
pending…

Compare results of other browsers

Revisions

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

0 Comments