4

除非我的测试有问题,否则当我在 Chrome 上运行这个 jsfiddle 时,$("#id")选择器大约需要 11 毫秒,选择器大约需要 56 毫秒$(div#id)

$(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

4 回答 4

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表单时使用它
  • 任何提供的上下文只会增加一个测试,并不会让它更快

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

于 2013-04-02T17:18:58.167 回答
2

自从我进入源代码以来已经有一段时间了,但我知道#some-id选择器document.getElementById()曾经tagName#some-iddocument.querySelectorAll.

于 2013-04-02T17:19:29.277 回答
1

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

于 2013-04-02T17:19:35.247 回答
0

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

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

于 2013-04-02T17:20:04.890 回答