4

Is there any benefit in using the data method when I can just store variables in plain javascript objects? It seems to me that using the jQuery data method is performance downgrade if it means re-looking up the DOM element to retrieve the value of the key, if the DOM element has not been referenced prior?

Sorry if this is painfully obvious to javascript devs, but I hope to understand this fully.

3 Answers 3

3

It's simply a case of convenience and it depends on your implementation as to whether you would use the data functionality. You would normally use .data() when you wanted to store related values for a specific DOM element or, more likely, a "collection" of DOM elements. You would normally then retrieve those values as you iterate through the elements and make a decision or perform an action based on the value. Even if you are going to retrieve one value - if you cached the jQuery DOM element(s) it would be an inexpensive call to retrieve the attached value.

2
  • +1 good point on the 'collection' bro! which I actually come across quite often but didn't cross my mind just...
    – bcm
    Mar 15, 2011 at 9:49
  • Also, using jQuery's data() will trigger events ("getData") on that object (an earlier version of jQuery.datalink relied on them but now uses a different approach). An example can be seen here: jsfiddle.net/algor/z2B8b/1 Mar 15, 2011 at 9:54
1

Because you cannot easily store data related to a certain DOM element using "plain javascript objects". If your data is not related to a certain DOM object you shouldn't use $.data of course!

3
  • Sorry if I don't make sense.. but isn't any relation implied just because they sit in the DOM? If so, can't I apply that (implied) relationship to an object array?
    – bcm
    Mar 15, 2011 at 9:03
  • Why store data related to certain DOM elements onto the DOM element itself? Rather than as a global variable which can be retrieved more quickly?
    – bcm
    Mar 15, 2011 at 9:16
  • 1) Global variables are dirty. 2) You need to retrieve the data specific to the DOM element. For an element without an ID.. how would you do that? Mar 15, 2011 at 10:18
0

I figured.

The DOM element can and should be referenced prior when using data, and that wouldn't result in a performance hit thus (and we still maintain the DOM_Element-key-value relationship).

So the initial look up for 'body' when storing the key-value is the only performance cost, and subsequent data retrievals don't have to find 'body' again:

b = $('body');
b.data('key', 'value');
alert(b.data('key'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.