function calls: direct vs apply vs call vs bind

JavaScript performance comparison

Revision 104 of this test case created by Ark

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  /**
   * @param {Function} fn - A Function
   * @param {*} context - A context
   *
   * @returns {Function}
   */
  
  function bindApply(fn, context) {
    return function boundApply() {
      return fn.apply(context, arguments);
    };
  }
  
  /**
   * @param {Function} fn - A Function
   * @param {*} context - A context
   *
   * @returns {Function}
   */
  
  function bindCall(fn, context) {
    return function boundCall() {
      return fn.call(context);
    };
  }
  
  /**
   * @param {Function} fn - A Function
   * @param {*} context - A context
   *
   * @returns {Function}
   */
  
  function bindCall1(fn, context) {
    return function boundCall1(arg) {
      return fn.call(context, arg);
    };
  }
  
  /**
   * @param {Function} fn - A Function
   * @param {*} context - A context
   *
   * @returns {Function}
   */
  
  function bindCallEvent(fn, context) {
    return function boundCallEvent(ev) {
      return fn.call(context, ev, this);
    };
  }
  
  /**
   * @param {Function} fn - A Function
   * @param {*} context - A context
   * @param {*} value - A value
   *
   * @returns {Function}
   */
  
  function bindCallValue(fn, context, value) {
    return function boundCallValue() {
      return fn.call(context, value);
    };
  }
  
  /**
   * DON'T USE THIS
   * -> Use myFunction.bind
   *
   * @param {Function} fn - A Function
   * @param {*} context - A context
   *
   * exemple :
   * var bindable = function(){return Array.prototype.slice.call(arguments);}
   * var binded = Utils.bindArgs(bindable, null, 1, 2, 3);
   *
   * binded('4'); => [1, 2, 3, '4']
   *
   * @returns {Function}
   */
  var arrProtSlice = Array.prototype.slice;
  var funProtBind = Function.prototype.bind;
  
  function bindArgs(fn, context) {
    return funProtBind.apply(fn, arrProtSlice.call(arguments, 1))
  }
  
  function myFunc(val) {
    return {
      ctx: this,
      args: arguments
    };
  }
  
  var myBinded = myFunc.bind({}, 1);

};
</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
apply
bindApply(myFunc, {})(1, 2, 3);
pending…
call
bindCall(myFunc, {})();
pending…
call1
bindCall1(myFunc, {})(1);
pending…
callEvent
bindCallEvent(myFunc, {})([]);
pending…
callValue
bindCallValue(myFunc, {}, 1)();
pending…
bindArgs
bindArgs(myFunc, {}, 1)(2, 3);
pending…
binded
myBinded(1)
pending…
closure
(function(self) {
  return myFunc.call(self, 1, 2, 3);
})({});
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