想象一下这个简化的标记:
<div id="header">
<!-- Other things.... -->
<div id="detail">
</div>
</div>假设你已经有了下面的代码:
var $hdr = $("#header");jQuery这样查找"detail“有速度上的区别吗?
var $detail = $("#detail", $hdr);vs
var $detail = $("#detail");因为详细信息是通过ID查找的?
发布于 2010-03-15 20:38:43
不,你没必要这么做。因为id在文档中是唯一的,所以不需要添加任何其他优化。
如果是我的话
var $detail = $("#detail");发布于 2010-03-16 03:40:18
不是的。传递上下文实际上会使它变得更慢。下面给出了来自jQuery的相关源代码及其解释。
这段代码基本上是这样说的:
1.然后执行一些操作,如调用document.getElementById()
这是经过剥离的源代码..
init: function( selector, context ) {
...
if ( typeof selector === "string" ) {
...
// This gets ignored because we passed a context
// document.getElementById() isn't called directly
if ( match && (match[1] || !context) ) {
...
} else {
elem = document.getElementById( match[2] );
...
}
...
// Either this gets executed if a jQuery wrapped context was passed
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
}
// Or this gets executed, if a simple selector was passed as context
} else {
return jQuery( context ).find( selector );
}
...
}
match是正则表达式的结果数组,用于确定选择器是HTML string还是id表达式。如果它是一个超文本标记语言字符串,那么match1将被填充。如果它是一个id (#someId),那么将填充match[2]。
发布于 2010-03-16 05:10:27
答案在于ID是如何存储的。分配的in保存在类似散列的数据结构中。如果搜索一个完全限定的ID (不是id*="foo"),那么所需的定位时间应该在没有任何修饰符的情况下是最快的,因为它是一个直接的散列查找。
https://stackoverflow.com/questions/2447076
复制相似问题