What is the performance cost of maintaining a live HTMLCollection?

Viewed 235

A piece of my front-end JS code is depending on a live HTMLCollection of several thousand DOM nodes. Since it is live, it updates automatically as the DOM is updated.

Is this the same as re-running thedocument.getElementsByClassName call every single time I modify the DOM, or is there a performance optimization under the hood?

1 Answers

This blog post explains a little of the difference between static and live NodeLists, and mentions how live collections are implemented.

A live collection doesn't access the DOM until you access its elements. At that time it creates the actual collection and caches it. There's no overhead to future accesses if the DOM doesn't change.

Changing the DOM shouldn't cause an immediate update to any collections. Rather, it should just invalidate their caches. The next time you access one of the collections, it will be regenerated.

So if you create a live collection and access it infrequently compared to DOM modifications, there should be relatively little overhead. The worst case is if you loop over a live collection and modify the DOM during the loop -- each iteration will have to update the collection.

It's possible that there may be additional optimizations that could mitigate this. For some types of live collections, the JavaScript engine may be able to tell whether a particular DOM modification could affect it; if not, it doesn't have to invalidate the collection. For instance, a collection created with document.getElementsByClassName() would not be affected by a modification that doesn't add or remove the specified class anywhere. However, if you do something like delete an element, it would have to check whether the class appeared anywhere in the subtree headed by that element, so it's not obvious that this would really be better than just invalidating the caches.

Related