Generally speaking, you will want to "cache" the results of the selector if you are sure that they will not change.
Your example is pretty trivial, as the #id selector is already quite efficient (in fact, it just passes it directly to the document.getElementById() call.
As already mentioned, you start to see savings when you use less efficient selectors (for example, $('.class') ).
Using variables in this way can save you a lot of extra processing. eg:
var tree = $('.bigTree'); // Do random stuff with tree // ... var segment = tree.find('.subsection'); // Do random stuff with segment...
In the above example, the segment variable can use the results of the variable tree without having to re-access the entire DOM, preserving this performance bit. While trivial examples like this are rarely worth it, to be sure that you are doing such things for bits of code (e.g. loops) can greatly speed up your application.
Of course, make sure that if you dynamically update the DOM, you use a "fresh" selector to make sure you select any changes :)
Owen source share