Dojo限制查询

Dojo restricting queries?

本文关键字:查询 Dojo      更新时间:2023-09-26

我正在阅读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呢?

仔细查看代码(http://svn.dojotoolkit.org/src/dojo/trunk/query.js用于查询和http://svn.dojotoolkit.org/src/dojo/trunk/selector/acme.js默认的选择器引擎)似乎"大"的性能改进来自于这样一个事实,即当您为查询方法提供document.getElementById("list")的一些帮助时,初始DOMNode列表会减少,但是似乎您只需要向查询方法传递父节点id的字符串,就可以实现相同的性能。

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

还有一个事实是,你可以通过将document.getElementById("list")的结果存储在一个变量中来缓存DOMNode列表并重用它。然而,在一般情况下,可读性(在这些琐碎的事情上)往往胜过性能。考虑到糟糕的JavaScript解释器可能隐藏的问题数量,拥有可读的代码最终会为您省去很多麻烦。