views:

60

answers:

1

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?

+1  A: 

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.

Nick Craver
I need this to store simple strings like "243px", "#333"... Not complex objects
Mircea
@Mircea - Then I personally would use data attributes if you have a consistent set of properties to store :)
Nick Craver
Will do so, thanx Nick
Mircea