0

Is there any way to find out if a javascript object that was referenced somewhere in the code is still alive and in memory?

the reason i ask is that my code got really complicated and I added some "cleanup" functions that are supposed to clear some of the references but I'm not sure if they work as they should. Can I somehow get a list of variables that are still in use by the browser?

Anna K.
  • 1,887
  • 6
  • 26
  • 38
  • 2
    As far as I know, in JavaScript you cannot perform clean up functions, it's the browser who decides when to do it. Can you please explain a little bit further what you have achieved? This answer may be useful: http://stackoverflow.com/a/18913692/738968 – Miguel Jiménez Aug 30 '15 at 00:59
  • You can say JavaScript does cleaning "automatically", but the delete keywords might be what you're looking for – Downgoat Aug 30 '15 at 01:02
  • 2
    If you want to check "a javascript object" that means you have a reference to that object, right? Then yes, it will be still in memory, because you have a reference to it. – Oriol Aug 30 '15 at 01:12

2 Answers2

3

In chrome, press F12 to open the debugger, then do the following:

  1. Click the [Timeline] tab
  2. Click the [Record] button in the top-left; play around with your site, open a menu, load a page, etc, where you want to check the memory.

enter image description here

  1. Whilst it's still recording, press the [garbage collector] and wait for a few seconds to let the buffer collect more data. Now press the [record] button again to stop the recording.

enter image description here

  1. Once the recording has stopped, you will see a 'stair-step' of how memory was allocated onto the heap.
  2. Importantly, you should see the lines return to zero after you hit the [garbage collection] button. If this doesn't happen, then you may have a memory-leak.

enter image description here

There are some very detailed videos from google advocates, explaining this debugger feature and is beyond the scope of this simplistic answer. This is just a pointer to a debugger feature you may want to use to test your code and find which objects are on the heap and if they're cleaned up as expected.

You can do further analysis of your objects with the [profiles] tab.

Data
  • 1,337
  • 11
  • 17
1

JavaScript is completely managed language and doesn't allow any kind of delete function.[delete keyword only deletes the properties but doesn't delete objects from memory] Best bet to clean any object is to assign to null to give a hint to garbage collector still may not work in all scenarios. Hope this helps

sumeet kumar
  • 2,628
  • 1
  • 16
  • 24