Created
July 26, 2012 17:33
-
-
Save cmer/3183364 to your computer and use it in GitHub Desktop.
Benchmarks for data(), attr() and getAttribute() over a large DOM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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