jQuery data function vs data attributes

Benchmark created by Ian on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  for (var i=0; i<100; i++) {
    $('<p>Here is a paragraph.</p>').data('index', i).attr('data-index', i).appendTo('body');
  }
});
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
data function
$('p').filter(function() { return $(this).data('index') === 20; }).css('color', 'red');
ready
data attributes
$('p[data-index="20"]').css('color', 'red');
ready
getAttribute
$('p').filter(function() { return this.getAttribute("data-index") === 20; }).css('color', 'red');
ready

Revisions

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