jQuery element selector
Are there any significant performance differences these two blocks of code?
var element = $("#some-element");
SomeMethod1(element);
SomeMethod2(element);
SomeMethod3(element);
and...
开发者_运维问答SomeMethod1($("#some-element"));
SomeMethod2($("#some-element"));
SomeMethod3($("#some-element"));
That depends on what you mean by significant
.
The first code snippet will always be faster than the second, because calling $()
more than once has a cost (as jQuery does not cache the results of previous calls). Whether it's significant or not depends on your performance requirements.
This does the element lookup in DOM and creates a jQuery object.
var element = $("#some-element");
In the first one, it reuses this object.
In second one, it has to do the lookup and creation 3 times, hence the first one is better performance wise.
Yes. First one is faster, second is slower
Why?
Because first searchs for element only once, second three times
It is not significant but not negligible also. In this case since you are using id selector it will not make much difference but if you going to use class selector or attribute selector then it will make a big difference.
The first one will always give you better performance than the second one because you are reusing the same object at multiple places.
Well, the first snippet reuses the first call to $("#some-element")
whilst the other example needs to lookup the #some-element
three times.
Latter:
- 3 string creations (the string literal holding the selector)
- 3 function calls to
$()
, each of which result in more function calls within - 3 searches of the document for the same element
Given the type of selector being used, I wouldn't say it's significant, but the latter requires more processing time and uses more memory (see above list). And that stuff adds up over the size of an app.
With a less direct selector, it could become significant much more quickly.
Edit: The latter, however, is ugly and drives me nuts. :)
精彩评论