getters and setters speedtest

Benchmark created by jurassicPieter on


Description

test what is the fastest for getters inside objects. of course closures are best OOP-wise, but are they also the fastest? I test 4 examples: use of closure function use of window.data use of this.data use of jQuery $.data

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
  var myObject1 = (function() {
    var foo = 42;
    return {
      getFoo: function() {
        return foo;
      },
      setFoo: function(val) {
        foo = val;
      }
    };
  }());
  window.foo = 42;
  var myObject2 = {
    'getFoo': function() {
      return window.foo;
    },
    'setFoo': function(val) {
      window.foo = val;
    }
  };
  var myObject3 = {
    'foo': 42,
    'getFoo': function() {
      return this.foo;
    },
    'setFoo': function(val) {
      this.foo = val;
    }
  };
  jQuery.data(document.body, 'foo', 42);
  var myObject4 = {
    'getFoo': function() {
      return jQuery.data(document.body, 'foo');
    },
    'setFoo': function(val) {
      jQuery.data(document.body, 'foo', val);
    }
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
save in closure
for (var i = 0; i < 30; i++) {
  myObject1.setFoo(i + myObject1.getFoo());
}
ready
save in window
for (var i = 0; i < 30; i++) {
  myObject2.setFoo(i + myObject2.getFoo());
}
ready
save in object
for (var i = 0; i < 30; i++) {
  myObject3.setFoo(i + myObject3.getFoo());
}
ready
use jQuery.data
for (var i = 0; i < 30; i++) {
  myObject4.setFoo(i + myObject4.getFoo());
}
ready

Revisions

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

  • Revision 1: published by jurassicPieter on