views:

24

answers:

1

Which of the following would theoretically be better with performance and / or memory? In other words, does jQuery have to do work to select the same item multiple times or does it know what items it has selected in the past?

I've intentionally left animate with no arguments, this is a purely theoretical question.

$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();
$("#someelement").animate();

or

var element = $("#someelement");
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
element.animate();
+3  A: 

Definitely option 2. With option 1 jQuery must find the element in th DOM before every animation.

With option 2 the element is "cached" in the variable and there's no need to traverse the DOM again.

Dave