Skip to content

Instantly share code, notes, and snippets.

@cmer
Created July 26, 2012 16:08
Show Gist options
  • Save cmer/3182945 to your computer and use it in GitHub Desktop.
Save cmer/3182945 to your computer and use it in GitHub Desktop.
Benchmarks for data(), attr() and getAttribute()
<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 addResult(desc, time) {
$('ul').append('<li>' + desc + ": " + time + "ms");
}
el = $('p')
startTime = new Date();
for (i=0; i<10000; i++) {
el.data("foo");
}
endTime = new Date();
addResult('data()', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
el.attr("data-foo");
}
endTime = new Date();
addResult('attr()', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
el[0].getAttribute("data-foo");
}
endTime = new Date();
addResult('getAttribute()', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
el.data("bar");
}
endTime = new Date();
addResult('data() non-existent', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
el.attr("data-bar");
}
endTime = new Date();
addResult('attr()', endTime - startTime);
startTime = new Date();
for (i=0; i<10000; i++) {
el[0].getAttribute("data-bar");
}
endTime = new Date();
addResult('getAttribute()', endTime - startTime);
</script>
<body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment