开发者

What are the javascript performance tradeoffs in adding id's to dom elements?

开发者 https://www.devze.com 2022-12-26 19:34 出处:网络
For example, I have a website which has a dynamically-generated segment of its dom which 开发者_JS百科looks roughly like this:

For example, I have a website which has a dynamically-generated segment of its dom which 开发者_JS百科looks roughly like this:

<div id="master">
  <div class="child"> ... </div>
  <div class="child"> ... </div>
  <div class="child"> ... </div>
  ...
  <div class="child"> ... </div>
</div>

There might be hundreds of child elements in this manner, and they, too, might have yet more children. At present, none of them have id's except for the master. Javascript manipulates them via dom-walking. It's a little scary.

I'd like to add id's, e.g.:

<div id="master">
  <div id="child1" class="child"> ... </div>
  <div id="child2" class="child"> ... </div>
  <div id="child3" class="child"> ... </div>
  ...
  <div id="childN" class="child"> ... </div>
</div>

What are the tradeoffs in adding id's to these divs? Certainly, jQuery must maintain a hash of id's, so there's going to be some sort of performance hit. Any general guidelines in when adding additional id's is a bad idea? Is jQuery so awesome that, in practice, it doesn't matter?


Certainly, jQuery must maintain a hash of ids

Nope. It's the browser that (optionally, as an optimisation) keeps a lookup of id to node.

If you interact with objects in a way that causes jQuery to add data to an element (including if you add an event listener), then it will add its own jquery-id to the element for lookup purposes. But it'll do that regardless of whether the element has an id attribute.

Add id​s if you need to pick out a particular element from the rest. But there's no point in adding childN attributes to every child when you already have classes. The selector #master>.child is likely to be faster than #master>[id^=child], and certainly much faster than fetching each idN separately in a loop.


IDs, being unique, are faster than classes when querying a page. They only apply to one element.

That being said, adding IDs to everything does add a lot of clutter to your code. Dom-walking from the parent is usually more convenient programming-wise now that frameworks do the heavy-lifting for us.

But often we want to perform functions on entire groups of elements. In this case, using classes makes sense. Doing a group function on a whole bunch of IDs would be inefficient.

Adding the IDs themselves does not add any performance hit, it all depends on how you intend to use your page.

0

精彩评论

暂无评论...
验证码 换一张
取 消