I have a global array containing the IDs of elements that I am currently working with. Every second I run a routine that does stuff to these elements.
var ids = ['abc', 'def', 'zyx']
// the following code happens every second
for (var i = 0; i < ids.length; i++) {
el = $("#" + ids[i])
// do stuff with el
}
My question: would I suffer a notable performance hit or improvement to do the following:
var ids = []
ids.push($("#abc"))
ids.push($("#def"))
ids.push($("#zyx"))
for (var i = 0; i < ids.length; i++) {
el = ids[i]
// do stuff with el
}
You don’t have to guess — why not create a jsPerf test case?
Anyhow, this change would greatly improve performance. There’s no reason to reconstruct jQuery objects for the same elements all the time.
My advice: keep things DRY — cache everything that can be reused.
Also note that instead of:
You could just do:
This saves a few function calls.