2

I was hoping to find out any information on practices to optimize for garbage collection or prevent object's from building up in memory over time.

As an example, let's say I have a continuous iteration and each time an item is added to an object.

Over time, older items added to the object are no longer relevant for the application, and should be removed from the object, they will never again be accessed. Is it necessary to specifically remove these values or would it continue to just build up into a huge object?

Thank you!

dzm
  • 22,844
  • 47
  • 146
  • 226
  • Garbage collector will never delete objects that are being pointed to. If you have `myObject = ...` and you're sure you won't need it anymore, just set `myObject = null` to break the link. – Imp Aug 23 '12 at 18:00
  • you should never need to say `myObject = null`, just let it get collected automatically when it goes out of scope. – jbabey Aug 23 '12 at 18:04
  • If you use the object and it has redundant properties, then those won't get cleared because you might be accessing them later. – pimvdb Aug 23 '12 at 18:05
  • @jbabey Of course, that destroys the link automatically. What I said must be done for global variables. But more importantly, this should be done for links between JS objects and DOM objects. Those may cause memory leaks, especially in everyone's favourite browser. – Imp Aug 23 '12 at 18:17
  • @Imp or just dont use global variables! :P – jbabey Aug 23 '12 at 18:19

1 Answers1

1

If it's your business logic that is dictating their uselessness, meaning there are still references to them, then Yes! You should explicitly remove these objects. In many cases you will want to wipe the object before breaking the references to ensure you're releasing everything you intend to release.

Ashley over at Scirra wrote a good primer on this earlier this year: How to write low garbage real-time Javascript

xelco52
  • 5,257
  • 4
  • 40
  • 56