data attributes

JavaScript performance comparison

Revision 7 of this test case created by ygally

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="mydiv"></div>
<script>
Benchmark.prototype.setup = function() {
    var div = document.getElementById('mydiv');
    var $div = $(div);
    var Data = function() {
      var warehouse = {};
      var count = 1;
      return {
        reset: function() {
          count = 1;
          warehouse = {};
        },
        set: function (dom, data) {
          if (!dom.__data) {
            dom.__data = "hello" + count++;
          }
          warehouse[dom.__data] = data;
        },
        get: function(dom) {
          return warehouse[dom.__data];
        }
      };
    }();
};

Benchmark.prototype.teardown = function() {
    div.setAttribute('data-po', null);
    div.setAttribute('data-ta', null);
    div.setAttribute('data-to', null);
    div['data-po'] = div['data-ta'] = div['data-to'] = null;
    div.setAttribute('__data', null);
    Data.reset();
    $div.data({
        "po": null,
        "ta": null,
        "to": null
    });
};
</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
old school setAttribute
div.setAttribute('data-po', 'to');
div.setAttribute('data-ta', 'ma');
div.setAttribute('data-to', 'to');
var a = div.getAttribute('data-po');
var b = div.getAttribute('data-ta');
var c = div.getAttribute('data-to');
pending…
DIY Data
Data.set(div, {po: 'to', ta: 'ma', to: 'to'});
var data = Data.get(div);
var a = data.po;
var b = data.ta;
var c = data.to;
pending…
HTML5 dataset
div.dataset.po = 'to';
div.dataset.ta = 'ma';
div.dataset.to = 'to';
var data = div.dataset;
var a = data.po;
var b = data.ta;
var c = data.to;
pending…
jQuery .data()
$div.data({
    "po": "to",
    "ta": "ma",
    "to": "to"    
});
var data = $div.data();
var a = data.po;
var b = data.ta;
var c = data.to;
pending…
old school []
div['data-po'] = 'to';
div['data-ta'] = 'ma';
div['data-to'] = 'to';
var a = div['data-po'];
var b = div['data-ta'];
var c = div['data-to'];
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. Here’s a list of current revisions for this page:

0 comments

Add a comment