data-method-part-2

JavaScript performance comparison

Test case created by Karl Mendes

Preparation code

<div id="bar1" class="bar" data-parent="foo">
</div>
<div id="bar2" class="bar" data-parent-element="foo">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var bar1 = document.getElementById('bar1'),
        bar2 = document.getElementById('bar2'),
        bars = document.getElementsByClassName('bar');
   
    data_karl = function(element, key, value) {
      var i, len;
      if (typeof element.length === 'undefined') {
        element = [element];
      }
      for (i = 0, len = element.length; i < len; ++i) {
        if (typeof value !== 'undefined') {
          element[i].setAttribute('data-' + key, value);
        } else {
          return element[i].getAttribute('data-' + key);
        }
      }
    };
   
    data_scheibe = function(element, key, value) {
      if (element.length === undefined) {
        if (typeof value !== 'undefined') {
          element.setAttribute('data-' + key, value);
        } else {
          return element.getAttribute('data-' + key);
        }
      } else {
        var i = -1,
            len = element.length - 1;
        while (i++ < len) {
          if (typeof value !== 'undefined') {
            element[i].setAttribute('data-' + key, value);
          } else {
            return element[i].getAttribute('data-' + key);
          }
        }
      }
    }
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
jQuery
$(bar1).data('parent');
$(bar2).data('parent-element');
$(bar1).data('null');
$(bar1).data('new', 'blah');
$(bars).data('blah', 'boom');
$(bars).data('parent');
pending…
Karl
data_karl(bar1, 'parent');
data_karl(bar2, 'parent-element');
data_karl(bar1, 'null');
data_karl(bar1, 'new', 'blah');
data_karl(bars, 'blah', 'boom');
data_karl(bars, 'parent');
pending…
Scheibe
data_scheibe(bar1, 'parent');
data_scheibe(bar2, 'parent-element');
data_scheibe(bar1, 'null');
data_scheibe(bar1, 'new', 'blah');
data_scheibe(bars, 'blah', 'boom');
data_scheibe(bars, 'parent');
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