Reputation: 967
When finding inner elements in a Backbone view, do you get optimal performance by limiting the scope to this.$el
, or does the find()
method still have to search through the whole DOM?
Here's a stub example of what I'm talking about:
<!-- a bunch of other stuff -->
<div id="outer">
<!-- a bunch of other stuff -->
<div id="inner">foo</div>
</div>
<!-- a bunch of other stuff -->
<script>
var myView = new MyView({el: $('#outer')});
</script>
where MyView is:
MyView = Backbone.View.extend({
//other code
useScoping: function() {
var $innerElement = this.$el.find('#inner');
$innerElement.text('bar');
},
noScoping: function() {
var $innerElement = $('#inner');
$innerElement.text('bar');
}
});
Will useScoping()
be more efficient than noScoping()
? I would think it would be since this.$el
has to be cached when the object is constructed, so that the search for '#inner'
doesn't have to cover the whole DOM when scoping is used. But I wanted to make sure. Would the same apply if we had class="inner"
with appropriate changes in the JavaScript?
Upvotes: 3
Views: 220
Reputation: 1110
If your worried about rendering performance the best solution is to save a variable with the jquery selector and always use that. When the model changes use the cached jquery selector to update the dom instead of re-rendering the template.
There's a bunch more tricks to make backbone views performant. I posted a backbone view subclass I'm working on at GitHub. https://github.com/puppybits/BackboneJS-PerfView It can render a collection with 1,000,000 models at over 90FPS. There's a bunch of optimizations in there with comments if your interested.
Upvotes: 1
Reputation: 3771
The performance will vary depending on the selector used. In the example you provided the #inner selector will lookup the element by ID which uses an internally maintained index and will not scan the document. Probably also true of selection using a class.
However, other selectors that don't have corresponding native implementations will have their performance improved by scoping.
// your examples will fall back to these native implementations and
// not be impacted by scoping
document.getElementById('inner')
document.getElementsByClassName('inner')
Upvotes: 4
Reputation: 102793
the search for '#inner' doesn't have to cover the whole DOM when scoping is used
You are correct. The Backbone view's this.$el
is just a proxy to the JQuery-wrapped element, and so this.$el.find
is just the JQuery find
, which searches only the descendents, not the whole DOM.
Upvotes: 1