How effecient is indexing into an HTMLCollection?

192 Views Asked by At

According to Nicholas Zakas, among others, HTMLCollections are so slow that copying the entire thing into an array is good practice if you are going to be accessing members repeatedly. He seems to claim that even using the indexers on HTMLCollections causes the collection to completely requery the DOM for all matching elements, as if the collection is actually a linq-esq expression tree, rather than a list of pointers leading straight to the elements.

I've got a situation where I need to allow easy keyboard navigation of tables. Every time someone hits one of the arrow keys, I need to switch focus from one table cell to another, and add and remove CSS classes accordingly. I thought about just storing the HTMLCollection of table rows returned by tableElement.rows, and accessing the individual cell elements through it. I know that HTMLCollections allow you to index into them as if they are arrays, and I assumed that this would be just as efficient as indexing into an array. Now I'm rethinking things, but I still want to understand why.

My question is this: What exactly happens under the hood when I call tableElement.rows[2].cells[6]?

0

There are 0 best solutions below