Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A simple test for seeing if it is faster to change a style or a class of an element.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="screen">
.hidden {
display:none;
}
</style>
</head>
<body>
<div class="show">
Here
</div>
<script type="text/javascript" charset="utf-8">
$(function(){
var divs = $('.show');
time = function(desc, fun) {
var start = new Date().getMilliseconds();
fun();
var total = (new Date().getMilliseconds() - start);
try {
console.log(desc + total);
} catch(err) {
alert(desc + total);
}
divs.show();
divs.removeClass('hidden');
};
time("changing style:", function(){
for(var i = 1; i < 1000; i++) {
divs.toggle();
}
});
time("changing class:", function(){
for(var i = 1; i < 1000; i++) {
divs.toggleClass('hidden');
}
});
});
</script>
</body>
</html>

Safari 5.0.2

  • changing style:123
  • changing class:15 - 87.8% faster

Chrome 7.0.517.44

  • changing style:115
  • changing class:16 - 86.1% faster

Firefox 3.0.15

  • changing style:333
  • changing class:99 - 70.3% faster

Firefox 3.6.12

  • changing style:261
  • changing class:60 - 77% faster

Opera 10.10

  • changing style:554
  • changing class:111 - 80% faster
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment