I measured performance for different approaches. Below are results.
First I generated a page with 10 thousand div tags on it:
<html>
<head>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="http://flesler-plugins.googlecode.com/files/jquery.rule-1.0.1.js"></script>
<script type="text/javascript" src="http://remysharp.com/time.js"></script>
<script type="text/javascript">
function changeStyles1() {
time.start("changeStyles1");
$("div.dv").css("background-color", "Silver");
$("a.lnk").css("color", "Black");
time.stop("changeStyles1");
time.report();
}
function changeStyles2() {
time.start("changeStyles2");
var html = "<style type='text/css'>.dv{background-color: Silver;} .lnk{color: Black;}</style>";
$("div#styles").html(html);
time.stop("changeStyles2");
time.report();
}
function changeStyles3() {
time.start("changeStyles3");
var html = "<style type='text/css'>.dv{background-color: Silver;} .lnk{color: Black;}</style>";
$("div#styles").html(html);
time.stop("changeStyles3");
time.report();
}
</script>
</head>
<body>
<div id="styles">
<style type="text/css">
.dv
{
background-color: Yellow;
}
.lnk
{
color: Red;
}
</style>
</div>
Change styles using:
<button onclick="changeStyles1();">
jquery selectors</button>
<button onclick="changeStyles2();">
global styles</button>
<button onclick="changeStyles3();">
jQuery.rule</button>
<div id="container">
<div class='dv'>div # 0 <br/><a href='about:blank' class='lnk'>Link # 0</a></div>
<div class='dv'>div # 1 <br/><a href='about:blank' class='lnk'>Link # 1</a></div>
<div class='dv'>div # 2 <br/><a href='about:blank' class='lnk'>Link # 2</a></div>
<div class='dv'>div # 3 <br/><a href='about:blank' class='lnk'>Link # 3</a></div>
<div class='dv'>div # 4 <br/><a href='about:blank' class='lnk'>Link # 4</a></div>
<div class='dv'>div # 5 <br/><a href='about:blank' class='lnk'>Link # 5</a></div>
...
</div>
</body>
</html>Example:
Change styles using:
div # 0
Link # 0
Link # 0
div # 1
Link # 1
Link # 1
div # 2
Link # 2
Link # 2
div # 3
Link # 3
Link # 3
div # 4
Link # 4
Link # 4
div # 5
Link # 5
Link # 5
Then I tested running time in IE7 and Mozilla 3.5:
| jQuery selectors | global styles | jQuery.rule | |
| IE7 | 2834 ms | 15 ms | 17 ms |
| Mozilla | 1108 ms | 10 ms | 6 ms |
Personally I prefer "global styles" approach cause in case when one has to change many styles at once it works faster than other methods and forces browser to update its stylesheet collection only once.
Used libraries:
No comments:
Post a Comment