Does interacting with variables in the following method cause any performance decline
Ok, so I have a reference to a div
stored in a variable, lets called it div_var
.
Now I want to do something to it; I can reference it in both the following ways;
div_var.animate()......
$(div_var).animate().....
The first way is obviously easier, the only problem is my code editor (Komodo开发者_如何学JAVA) won't offer any code hinting/code completion for it. The second way gives me full code hinting but I don't know if I'm taking a performance hit for it.
Felix Kling was correct, it is slower. I created a simple test
HTML
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body style="width: 600px;">
<p class="t1-start">1</p>
<p class="t2-start">1</p>
</body>
</html>
JS (test.js)
jQuery(document).ready(function($) {
var num = $('.t1-start')
var num2 = $('.t2-start')
firstCount()
function firstCount(){
var time = new Date()
var start = time.getTime()
for (var i=0; i < 10000; i++) {
$(num).append(' 1');
}
var time2 = new Date()
var end = time2.getTime()
var leng = end - start;
var leng_string = '<h1>'+leng+'</h1>'
$(num).replaceWith(leng_string)
secondCount()
}
function secondCount(){
var time = new Date()
var start = time.getTime()
for (var i=0; i < 10000; i++) {
num2.append(' 1');
}
var time2 = new Date()
var end = time2.getTime()
var leng = end - start;
var leng_string = '<h1>'+leng+'</h1>'
$(num2).replaceWith(leng_string)
}
})
the first loop is consistently about 15-20% slower.
If div_var
is already a jQuery object, then passing it to jQuery again is superfluous.
Whether it has influence on the performance depends on your application. Fact is, it is an additional, unnecessary function call.
精彩评论