var self = this; vs function(){}.bind()

JavaScript performance comparison

Test case created by Greg Miell

Info

See setup for tests, this looks at the speed different between taking a reference to the current this context verses using function.bind

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function TestObj () {
      this.array = [];
      for (var i = 0; i < 2000; i++)
        this.array.push(i);
    }
    TestObj.prototype.test_self = function () {
      var self = this;
      this.array.forEach(function (val, index) {
        self.array[index] = val * 2;
      });
    }
    TestObj.prototype.test_bind = function () {
      this.array.forEach(function (val, index) {
        this.array[index] = val * 2;
      }.bind(this));
    }
    var test_obj = new TestObj;
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
var self = this;
test_obj.test_self()
pending…
function.bind
test_obj.test_bind()
pending…

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

Compare results of other browsers

0 comments

Add a comment