1

If I have a backbone model on the server (node.js) and insert data on each route (using Express), will that model grow infinitely? Should I clear memory manually when the model has performed what it was supposed to do?

Pseudo-example:

var model = require('./model')

route.index = function() {
    var key = new Date()
    model.set(key, 'foobar')
    console.dir(model.toJSON())
}

On each reload in the browser, this model will grow. My question is: do I need to manually empty the model or is there a "garbage collector" in node that will take care of this?

David Hellsing
  • 97,234
  • 40
  • 163
  • 203
  • In `'./model'` are you exporting a new model? ie `module.export = new Backbone.Model()` – Cory Danielson Apr 08 '15 at 21:49
  • @CoryDanielson yea, but it’s actually a collection. Not that it would make a difference right? – David Hellsing Apr 08 '15 at 22:09
  • Nah, no difference. I was just wondering... Singletons can get kinda hard to work with... I've actually been struggling with one all day at work myself. http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – Cory Danielson Apr 08 '15 at 23:01

1 Answers1

0

There is a garbage collector in Node, but it won't clean up this model, because it's always referenced in your code.

Node will be able to clean it up once you break the reference by destroying the model, or saving a new variable in it's place.. or by occasionally emptying it's attributes.

if ( _.keys(model.attributes).length > 1000 ) {
    model.attributes = _.result(model, 'defaults') || {}; // reset the model to it's default values
    // or model = new Backbone.Model();
}

But this seems like an unsafe thing to do since this model can be used elsewhere.

Cory Danielson
  • 13,192
  • 3
  • 42
  • 49
  • 1
    `Model.set` also takes an object as argument, but thats not the point (it’s just a pseudo-code example). I’m just asking how node.js will deal with code like this, f.ex if I need to manually clear the model on each request. – David Hellsing Apr 08 '15 at 21:39
  • Your syntax was wrong. `model.set({key:"foobar"}` will set the "key" property to "foobar" every single time. No memory leak. You would have to do `model.set(key, "foobar")` or ES6 `model.set({[key]: "foobar"})` to introduce the memory leak. – Cory Danielson Apr 08 '15 at 21:42