javascript - id太多会影响性能吗

标签 javascript jquery html asp.net-mvc performance

如果我在页面中的元素上有不必要的 id,例如 ASP.Net-MVC 中的 HTML Helper
它会降低我的 id 选择器的性能吗? (我有一个包含大量元素的页面)

示例:

// First DOM   
<HTML>
...
    <input type="text" value="first" id="useless" />
    <input type="text" value="second" id="useful" />
</HTML>

// Second  DOM  
<HTML>
...
    <input type="text" value="first"/>
    <input type="text" value="second" id="useful" />
</HTML>

脚本:

<script>
    alert($('#useful').val());
    // never select the first element (with the useless id)
</script>

最佳答案

简答,不。

http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/

A few months back there were some posts about the performance impact of inefficient CSS selectors. I was intrigued – this is the kind of browser idiosyncratic behavior that I live for. On further investigation, I’m not so sure that it’s worth the time to make CSS selectors more efficient. I’ll go even farther and say I don’t think anyone would notice if we woke up tomorrow and every web page’s CSS selectors were magically optimized...

I revised the test as follows:

  • 2000 anchors and 2000 rules (instead of 20,000) – this actually results in ~6000 DOM elements because of all the nesting in P, DIV, DIV, DIV
  • the baseline page and tag selector page have 2000 rules just like all the other pages, but these are simple class rules that don’t match any classes in the page

I ran these tests on 12 browsers. Page render time was measured with a script block at the top and bottom of the page. (I loaded the page from local disk to avoid possible impact from chunked encoding.)...

Based on these tests I have the following hypothesis: For most web sites, the possible performance gains from optimizing CSS selectors will be small, and are not worth the costs. There are some types of CSS rules and interactions with JavaScript that can make a page noticeably slower. This is where the focus should be...

关于javascript - id太多会影响性能吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9193293/

相关文章:

javascript - 如何在 jQuery 中对具有一个共同特定属性的两个对象的值求和?

javascript - 克隆行时清除隐藏输入

javascript - 当您放置刚才单击的 'a' 时如何保持(并显示)当前 'history.back()' 元素

javascript - 如何在没有输入类型的情况下禁用复选框?

javascript - 我如何显示 GroupLists 的 FormArray?

javascript - 如何解析此 HTML javascript 页面中的日期?

javascript - 使用javascript在div中显示输入字段值

javascript - 停留在这个 jquery 插件的结构上

html - CSS:在子元素中显示有序列表项索引

javascript - JS - 如何在 Google Graphs (slantedText) 上旋转标签 (hAxis)?