jQuery().fn.attr vs jQuery().fn.prop vs jQuery().fn.data vs jQuery().data (v12)

Revision 12 of this benchmark created by SMR on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="el"></div>
<script>
  // 'el-lo
  var $el = $('#el');
  var el  = $el[0];
  var get; // access holder, so that dead stores aren't so easily culled off.
  
  // Store only 19 strings to test.
  // In real code, there usually are not very many
  // unique keys that get accessed and mutated. 
  // It needs to be odd so that after counter%limit loops,
  // the attr/prop/data accessors return values.
  // This also shakes up the key/value pairs.
  var counter, limit = 19;
  var rnd = [];
  
  // Pre-create all strings unique, just to make sure nothing funny happens.
  for (var i = 0; i < limit; i++) {
      rnd[i] = 'X-' + i + '-' + Math.floor(Math.random() * 1001);
  }
  
  function nextKey() { return rnd[counter++ % limit]; }
  function nextVal() { return rnd[counter++ % limit]; }
  
</script>

Setup

counter = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery.fn.attr
$el.attr(nextKey(), nextVal());
get = $el.attr(nextKey());
ready
jQuery.fn.prop
$el.prop(nextKey(), nextVal());
get = $el.prop(nextKey());
ready
jQuery.fn.data
$el.data(nextKey(), nextVal());
get = $el.data(nextKey());
ready
jQuery.data(el)
$.data(el, nextKey(), nextVal());
get = $.data(el, nextKey());
ready
jQuery.data($el)
$.data($el, nextKey(), nextVal());
get = $.data($el, nextKey());
ready

Revisions

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