In this specific instance, it does not really matter. Here is my rationale:
In any case, in Sizzle (the selector library used by jQuery), a lookup for a simple #identifier
selector (e.g. $("#identifier")
) is probably the fastest around, since apart from error checking and browser compatibility check (apparently, some browsers, like older versions of IE, will not consider dynamically-added id
attributes). it results in little more than simply translating it to a document.getElementById(selector) call. That DOM selection method is the fastest, since browsers will hash the identifiers for quick lookups, because they are required by specification to be unique inside a
Although it is good practice, in this case the performance gain is probably very negligible, when compared to a much more complex selector such as element > .class:not-first:has(element.class2) + li
. And according to this answer the most recently used identifiers are cached anyway.
Bottom-line: in your situation, disregard the performance gains, they are negligible. Premature optimization is the root of all evil. Just consider the overall cleanliness of code: arguably, repeating the same selector call in a single line of code is not as clean as referencing the selector in a variable (DRY), which has the added benefit of being easily replaceable, or even parameterizable.