Skip to content

Instantly share code, notes, and snippets.

@cmer
Created July 26, 2012 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmer/3183364 to your computer and use it in GitHub Desktop.
Save cmer/3183364 to your computer and use it in GitHub Desktop.
Benchmarks for data(), attr() and getAttribute() over a large DOM
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<ul></ul>
<p data-foo='abc'></p>
<script>
function random()
{
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
nodes = "";
for (x=0; x<10000; x++) {
nodes += "<div data-foo='" + random() + "'></div>";
}
$(nodes).insertAfter($('p'));
function addResult(desc, time) {
$('ul').append('<li>' + desc + ": " + time + "ms");
}
el = $('div')
startTime = new Date();
for (i=0; i<10000; i++) {
$(el[i]).data("foo");
}
endTime = new Date();
addResult('data()', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
$(el[i]).attr("data-foo");
}
endTime = new Date();
addResult('attr()', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
el[i].getAttribute("data-foo");
}
endTime = new Date();
addResult('getAttribute()', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
$(el[i]).data("bar");
}
endTime = new Date();
addResult('data() non-existent', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
$(el[i]).attr("data-bar");
}
endTime = new Date();
addResult('attr() non-existent', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
el[i].getAttribute("data-bar");
}
endTime = new Date();
addResult('getAttribute() non-existent', endTime - startTime);
</script>
<body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment