Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The optimisation mentioned by the grandparent is specific to looping overso-called "live" collections of the DOM. NodeList [0] is sometimes a live collection, and is the return type of querySelectorAll, so it's likely you've dealt with this type of collection.

The reason it incurs an overhead is because the DOM is traversed every single time the property is read, to ensure nothing has changed. You can see why caching the length is a reasonable optimisation, as you're unlikely to be modifying the collection while looping.

[0] https://developer.mozilla.org/en/docs/Web/API/NodeList



Exactly. Although, I am curious if there's a reason the JS engine (possibly working with the DOM implementation) can't optimize that to one look-up, if the JS in the loop doesn't change that part of the DOM or call anything that forces it to yield.

I suspect a lot of the optimization opportunity in browsers today is less about JS or DOM in isolation but more about ways they could work together to improve situations like this one.

(Note: I understand this one is solvable by a proficient/attentive developer, but not all developers are like that, and not all such DOM/JS transition problems are as easily solvable from your JS code)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: