Dojo限制查询?

时间:2012-02-13 23:11:31

标签: javascript dojo

我正在阅读dojo查询教程并看到了

// retrieve an array of nodes with the class name "odd"
// from the first list using a selector
var odds1 = query("#list .odd");

// retrieve an array of nodes with the class name "odd"
// from the first list using a DOM node
var odds2 = query(".odd", document.getElementById("list"));

他们解释说odds2比odds1快,因为odds2在#list dom中搜索.odd而不是整个html dom。我想知道做odds1的优点是什么(除了更干净的代码,我猜)?因为在我看来查询在id元素中搜索对象的任何情况都应该始终使用odds2样式(假设正确的id,类html使用),那么为什么dojo不会自动解析odds1中的查询字符串来调用odds2?

1 个答案:

答案 0 :(得分:2)

仔细查看代码(http://svn.dojotoolkit.org/src/dojo/trunk/query.js查询和http://svn.dojotoolkit.org/src/dojo/trunk/selector/acme.js默认选择器引擎),看来“大”性能改进来自于当您提供时初始DOMNode列表减少的事实查询方法对document.getElementById("list")提供了一些帮助,但是看起来您只需将查询方法传递给父节点的id字符串并获得相同的性能。

query(".odd", "list");

然后,您可以通过将document.getElementById("list")的结果存储在变量中并重用它来缓存DOMNode列表。然而,一般来说,可读性(在这个微不足道的事情上)往往胜过性能。考虑到错误的JavaScript解释器可以隐藏的问题数量,拥有可读代码最终可以为您节省很多麻烦。