Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That explains it, along with the fact that getAttribute('data-*')/setAttribute() seem to be faster in microbenchmarks[1] than getting/setting properties on element.dataset. Thanks for clearing this up, I'd have never guessed that about dataset!

[1]https://jsperf.com/dataset-vs-getattribute-and-setattribute/...



Yeah, a get on a dataset has to do strictly more work than getAttribute: it has to convert the string it has to a "data-whatever" string and then call getAttribute.

But note that in microbenchmarks you are likely to get some confusing effects. For example, in Firefox this microbenchmark:

  document.getElementById('test').getAttribute('data-set')
will get optimized as follows:

1) getAttribute is known to be side-effect free when called with a string argument, its return value is not used, the call can be dead-code eliminated.

2) getElementById is known to be side-effect free when called with a string argument, its return value is not used after step 1, the call can be dead-code eliminated.

3) The get of the "document" property is known to be side-effect free, its return value is not used after step 2, the get can be dead-code eliminated.

So in the end the microbenchmark is measuring how fast the browser can increment a loop counter, and that only because we haven't bothered to try dead-code eliminating that. That's why you get numbers in the billions of operations per second range (comparable to the CPU clock speed; always a dead giveaway that your thing got optimized out). ;)

Note that Firefox will also perform loop-hoisting on all of the above if possible, so even if the return value were assigned somewhere that would not matter: the whole thing would just get hoisted out of the loop.

The setAttribute and "dataset.set = stuff" benchmarks don't have these problems, because those operations are clearly not side-effect free. A sufficiently advanced JIT might be able to determine that earlier iteration assignments are dominated by later ones and eliminate them, but now we're talking quite hard work on the part of the browser.


Yes, after watching so many of Vyacheslav Egorov's (from V8) talks on microbenchmarking, I'm convinced that JIT's are doing some serious witchcraft unmeasurable by microbenchmarks; yet googling relevant tests on jsperf is tough habit to shake off. As this example shows.

While we are on the subject, can I ask if there are any performance advantages of using data attributes over custom attributes for storing data in an element? In other words, can adding non-standard attributes to an element cause any deoptimizations? I know that JS engines use hidden classes/object shapes to optimize JS objects, I assumed something similar might be the case for DOM elements, in that case adding non-standard attribute must mean deoptimization.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: