Binding Call vs. Calling

Benchmark created by Sean Vieira on


Description

When aliasing useful methods (Array.prototype.slice, anyone) you can either:

  • Bind a variable to the name and then .call or .apply it:

    <span class="kw2">var</span> slice <span class="sy0">=</span> Array.<span class="me1">prototype</span>.<span class="me1">slice</span><span class="sy0">;</span><br><span class="co1">// And then later:</span><br>slice.<span class="me1">call</span><span class="br0">(</span>arguments<span class="br0">)</span><span class="sy0">;</span>
  • Or bind Function.prototype.call to the method, allowing you to treat it like a function again:

    <span class="kw2">var</span> fcall <span class="sy0">=</span> <span class="kw2">Function</span>.<span class="me1">prototype</span>.<span class="me1">call</span><span class="sy0">,</span><br>&nbsp; &nbsp; slice <span class="sy0">=</span> fcall.<span class="me1">bind</span><span class="br0">(</span>Array.<span class="me1">prototype</span>.<span class="me1">slice</span><span class="br0">)</span><span class="sy0">;</span><br><span class="co1">// And then later:</span><br>slice<span class="br0">(</span>arguments<span class="br0">)</span><span class="sy0">;</span>

The question is, do we pay a performance penalty for the cleaner syntax?

Setup

var applicativeSlice = Array.prototype.slice,
        callableSlice = Function.prototype.call.bind(Array.prototype.slice);
    
    function applicativeToArray() {
        return applicativeSlice.call(arguments);
    }
    
    function callableToArray() {
        return callableSlice(arguments);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
[].slice.call
applicativeToArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
ready
Function.fn.call.bind([].slice)
callableToArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
ready

Revisions

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

  • Revision 1: published by Sean Vieira on