I have a use case which requires getting multiple html5 data-attributes from elements. This occurs within a loop across many elements and pushes the data in to an array for caching.
From doing some research it appears that using el.getAttribute('data-whatever')
is faster than using the native html5 dataset
method however I need to get around 5 separate data attributes from the same element.
The dataset
method allows you to retrieve all data-attributes with one call and then access them with standard object dot notation ( dataset.index, dataset.whatever, dataset.somethingelse ) whereas using getAttribute
I have to make repeated getAttribute calls to retrieve all the needed data.
If using non pliant attributes I can of course simply use dot notation to access the properties speeding up this function considerably. But using html5 data attributes this does not work (i.e. el.data-whatever will always be undefined).
I wish to remain pliant to standards therefore I am looking for the fastest possible way of retrieving these multiple data attributes.
Thanks in advance.
I have a use case which requires getting multiple html5 data-attributes from elements. This occurs within a loop across many elements and pushes the data in to an array for caching.
From doing some research it appears that using el.getAttribute('data-whatever')
is faster than using the native html5 dataset
method however I need to get around 5 separate data attributes from the same element.
The dataset
method allows you to retrieve all data-attributes with one call and then access them with standard object dot notation ( dataset.index, dataset.whatever, dataset.somethingelse ) whereas using getAttribute
I have to make repeated getAttribute calls to retrieve all the needed data.
If using non pliant attributes I can of course simply use dot notation to access the properties speeding up this function considerably. But using html5 data attributes this does not work (i.e. el.data-whatever will always be undefined).
I wish to remain pliant to standards therefore I am looking for the fastest possible way of retrieving these multiple data attributes.
Thanks in advance.
I made this test:
http://jsperf./dataset-vs-getattribute-2
The test is a the following:
dataset all:
var data = el.dataset;
getAttribute all:
var data = {
id: el.getAttribute('data-id'),
user: el.getAttribute('data-user'),
dateOfBirth: el.getAttribute('data-date-of-birth')
};
dataset single:
var user = el.dataset.user;
getAttribute single:
var user = el.getAttribute('user');
https://developer.mozilla/en-US/docs/Web/API/element.dataset
Just benchmark it :
http://jsperf./dataset-access-vs-getattrb
It still looks to be 2 times faster using getAttribute
on chrome.
I'm using a noop
to prevent the JIT from optimizing it away.