template.find() vs document.querySelector vs jquery vs template.$ Meteor 中的性能

template.find() vs document.querySelector vs jquery vs template.$ performance in Meteor

我知道用template.find()template.$在Meteor中搜索DOM比用document.querySelector()或[=搜索所有DOM要快23=]。但是不知道快了多少。 我想这将与应用程序的 DOM 节点数直接相关,但我不知道是否是这种情况,或者 Meteor 中是否有任何其他 optimization/degradation 使得这个假设不那么成比例。 有人知道这方面的表演 test/result 吗?

我不能说我注意到我的用户有任何真正的性能提升,但我会说 template.find() 似乎让我的代码性能得到提升。

例如

var someID = $('#some-id');

在我像这样添加数组插槽之前将无法管理:

var someID = $('#some-id')[0];

其中

var someID = template.find('#some-id')

Returns 只是那个 html 元素,这意味着我不必每次都将其视为数组。

template 不等于 document。一个 document 可以包含许多 templatetemplate.find abstracts $, but template.find doesn't add any functionality. So template.$ and template.find will more or less perform equally. $ is a common alias for jQuery and when you pass a single string to the jQuery function it'll go through a few more abstractions and probably land on document.querySelector. That's why document.querySelector is a lot faster than jQuery(jsperf 正在关闭,所以我无法告诉您快了多少)。 jQuery 慢得多,在大多数情况下,它可能是 document.querySelectortemplate.$ 之间的一个近距离通话。

通过获取一个包含目标的节点然后使用 native-DOM 函数,您将获得最佳性能。如果您的模板中有一个包装元素,您可以使用 template.firstNode 属性。否则你可以像 blaze 那样做:template.firstNode.parentElement。然后我会使用 getElementsByClassNamegetElementById。它们比 querySelector 更快,因为使用 querySelector 必须首先解析查询。至少在大多数情况下,它取决于包装节点中的节点数以及您要搜索的元素在树中的距离。