I was having an issue where jQuery’s .data() seemed extremely slow in a particular scenario. I ran benchmarks for .data(), .attr() and .getAttribute() which essentially all do the same thing and the results were astonishing.
In Chrome 20 and Firefox 13.0.1 running on my 2009 iMac, 10,000 runs on a single element gave me the following results:
|.data() invalid attribute||117ms||179ms|
|.attr() invalid attribute||22ms||71ms|
|.getAttribute() invalid attribute||1ms||3ms|
It seems like .data() is about 30-40% slower when the attribute does not exist.
The code I used for this first test is here: https://gist.github.com/3182945
.getAttribute() seemed a bit too fast so I wondered if my benchmarks were wrong or flawed because I was constantly fetching the data of the same element. I decided to rewrite my benchmarking code to actually loop a 10,000-element DOM, which is more realistic. Here are my results:
|.data() invalid attribute||133ms||232ms|
|.attr() invalid attribute||25ms||106ms|
|.getAttribute() invalid attribute||3ms||5ms|
It looks like my first benchmarks were pretty much representative of the reality. We get the same kind of performance gap over a large DOM.
The code for this second test is here: https://gist.github.com/3183364
It’d be interesting to see how other browsers compare…