template.find() vs document.querySelector vs jquer

2019-05-21 03:01发布

I know that using template.find() or template.$ to search the DOM in Meteor is faster than searching all the DOM with document.querySelector() or jQuery. But I don't know how much faster. I imagine it would be directly related to the number of DOM nodes of the app but I don't know if that's the case or if there's any other optimization/degradation in Meteor that makes this assumption not so proportional. Does anyone know about a performance test/result on this?

2条回答
SAY GOODBYE
2楼-- · 2019-05-21 03:25

template is not equal to document. A document can contain many templates. template.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 is down right now, so I can't tell you how much faster). jQuery is so much slower, that in most cases it'll probably a close call between document.querySelector and template.$.

You'll get the best performance by getting a hold of a node wrapping your target and then using native-DOM functions. If you had a wrapping element inside your template, you could use the template.firstNode property. Otherwise you can just do what blaze does: template.firstNode.parentElement. Then I'd use getElementsByClassName or getElementById. They are faster then querySelector because with querySelector the query has to be parsed first. At least most of the time it depends on the number of nodes in your wrapping node and how far inside the tree the element your searching for is.

查看更多
Bombasti
3楼-- · 2019-05-21 03:48

I can't say that I've noticed any real performance increase for my users, but I will say that template.find() seems to give me a performance boost in how I code.

For example

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

Will not be manageable until I add an array slot like so:

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

Where as

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

Returns just that html element, meaning I don't have to treat it like an array every time.

查看更多
登录 后发表回答