Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .data() vs HTML5 data-XXX performance

I found this test http://jsbin.com/ekofa/2 that shows that HTML5 data-XXX is faster then jQuery .data(). I am starting a project that require lots of small data pieces placed on HTML elements where performance is crucial. Should I use .data() or HTML5 data-XXX? Is that test relevant and accurate?

like image 275
Mircea Avatar asked Dec 13 '25 07:12

Mircea


1 Answers

It depends where you're coming from I suppose, but for storing simple properties, data-XXX will be faster just because of how $.data() and .data() work.

For example when you do this to get data:

var thing = $('#myelement').data('thing')

What you're actually doing is this:

var thing = $.cache[$('#myelement')[0][$.expando]]['thing'];

This is longer than fetching an attribute directly, like this:

$('#myelement').attr('thing')

So with data you're actually getting the $.expando attribute just to get the ID then going to $.cache to get the object, this extra step means it will be consistently slower.

Then again, data-xxx attributes weren't meant for storing event handlers or other really complex objects that you're actively manipulating...so they aren't a 1:1 in their application so a direct comparison may not be fair. Though they're used for the same things in many cases, they also have different applications that aren't common to both...so keep that in mind when picking what to use. This is usually true of any 2 mostly common technologies IMO.

like image 169
Nick Craver Avatar answered Dec 14 '25 19:12

Nick Craver