为什么$(div#id)比$(#id)慢?

时间:2013-04-02 17:18:00

标签: javascript jquery performance google-chrome

除非我的测试出现问题,否则当我在Chrome上运行此jsfiddle时,$("#id")选择器大约需要11ms,而$(div#id)选择器大约需要56ms。

$(document).ready(function(){
    startTime = new Date().getTime();
    for (i = 0; i < 10000; i++)
    {
        s = $("#idC12");
    }           
    $("#idResults").html("c12 by id only time: "+elapsedMilliseconds(startTime));

    startTime = new Date().getTime();
    for (i = 0; i < 10000; i++)
    {
        s = $("div#idC12");
    }           
    $("#classResults").html("c12 by tagname#id: "+elapsedMilliseconds(startTime));
});

function elapsedMilliseconds(startTime)
{
    var n = new Date();
    var s = n.getTime();
    var diff = s - startTime;
    return diff;
}

http://jsfiddle.net/MhWUc/

4 个答案:

答案 0 :(得分:11)

这是因为$("#id")内部使用了本地document.getElementById函数,该函数使用从id链接到具有此id的(唯一)元素的映射。

这是jQuery源代码中的相关代码:

        // Easily-parseable/retrievable ID or TAG or CLASS selectors
        rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/
        ...
        // Speed-up: Sizzle("#ID")
        if ( (m = match[1]) ) {
            if ( nodeType === 9 ) {
                elem = context.getElementById( m );
                // Check parentNode to catch when Blackberry 4.6 returns
                // nodes that are no longer in the document #6963
                if ( elem && elem.parentNode ) {
                    // Handle the case where IE, Opera, and Webkit return items
                    // by name instead of ID
                    if ( elem.id === m ) {
                        results.push( elem );
                        return results;
                    }
                } else {
                    return results;
                }
            } else {
                // Context is not a document
                if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
                    contains( context, elem ) && elem.id === m ) {
                    results.push( elem );
                    return results;
                }
            }

你会注意到:

  • 当正则表达式检测到#someId表单
  • 时使用它
  • 任何提供的上下文仅添加测试,并且不会使其更快

请注意,在定义CSS规则或使用document.querySelector时,此规则在jQuery之外仍然适用:当您知道id时,没有什么比使用document.getElementById更快(除了缓存的元素.. )。

答案 1 :(得分:2)

自从我进入源代码以来已经有一段时间,但我知道#some-id选择器曾经由document.getElementById()处理,而更复杂的选择器(例如,tagName#some-id)必须经历嘶嘶声并最终通过document.querySelectorAll

答案 2 :(得分:1)

$('div#id')速度较慢,因为它不会直接映射到本机getElementById()方法。

答案 3 :(得分:0)

当你使用div#id时,首先选择所有的div。

当您使用#id时,它会直接转到ID表。