Backbonejs Rendering Collection With Document Fragment
JavaScript performance comparison
Info
Rendering Collection Views with document frament vs appending to a div directly
Preparation code
<div id='target'>
</div>
<div id='existing'>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.1/underscore-min.js">
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
var Item = Backbone.Model.extend({});
var Items = Backbone.Collection.extend({
model: Item
});
var ItemView = Backbone.View.extend({
render: function() {
this.$el.html($("<div class='itemview'></div>"));
return this;
}
});
var ItemsViewOne = Backbone.View.extend({
render: function() {
var fragment = document.createDocumentFragment();
_.each(this.collection.models, function(item) {
var x = new ItemView({
model: item
});
fragment.appendChild(x.render().el);
}, this);
this.$el.html(fragment);
return this;
}
});
var ItemsViewTwo = Backbone.View.extend({
render: function() {
_.each(this.collection.models, function(item) {
var x = new ItemView({
model: item
});
this.$el.append(x.render().el);
}, this);
return this;
}
});
var ItemsViewThree = Backbone.View.extend({
el: "#existing",
render: function() {
this.$el.html("");
_.each(this.collection.models, function(item) {
var x = new ItemView({
model: item
});
this.$el.append(x.render().el);
}, this);
return this;
}
});
// reasonable number of models
var items = new Items();
for (var i = 0; i < 20; i++) {
items.add({});
}
};
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Using Document Fragment |
|
pending… |
Appending Directly |
|
pending… |
Appending to existing dom element |
|
pending… |
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
- Revision 1: published by ymichael
- Revision 4: published by Antti Ahti and last updated
- Revision 5: published
0 comments