Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Identify A Memory Leak with Backbone.js

I believe I have a memory leak in my Backbone.js app. I concluded this after I printed some of my Backbone.View objects to the console, and saw the cid #'s increasing to the hundreds after just a bit clicking around.

Is this increasing cid# a sure sign of a memory leak? Are there any Heap profiling tools I can see the objects that are created, like with Java language? What are the best practices with Backbone.js to ensure no leaks?

Thanks!

like image 662
aarosil Avatar asked Dec 15 '22 05:12

aarosil


2 Answers

The best practice is to use listenTo instead of on and bind. And do not forget to stopListening when you remove an instance.

I would suggest to use Chrome profiler for leaks detection: https://developers.google.com/chrome-developer-tools/docs/javascript-memory-profiling.

Also you can try to use Chrome plugin for debugging Backbone apps: https://github.com/Maluen/Backbone-Debugger for debugging Backbone apps.

like image 73
Vitalii Petrychuk Avatar answered Jan 31 '23 08:01

Vitalii Petrychuk


The profiler is the only source to find out where the leaks are. But there's a much simpler way to see the bigger picture. Go to the timeline then memory in chrome dev tools. It's much easier to read the graph and will show you spikes in memory and DOM creation/destruction.

You shouldn't worry about cleaning leaks until you're app manages the memory as best as possible. Users WILL notice memory spikes because the app will chug; They WON'T notice 99.9% of the leaks.

You're time would be better spend learning how to manage memory in the browser. Backbone doesn't do a good job managing memory. To use memory better: Use object pooling on DOM nodes, update DOM elements when the model changes, keep as much javascript as possible out of the templates, only use the render function once, be careful when loading images. There's a lot of techniques. Here's an example of the techniques to make you're backbone app performant: https://github.com/puppybits/BackboneJS-PerfView.

like image 42
puppybits Avatar answered Jan 31 '23 08:01

puppybits