Part 1 - Null vs Delete

Rather than making a huge blog post about all the possible ways of circumventing memory leaks in javascript, I decided to break it into smaller and more maintainable chunks. Lets admit it there are a lot of things to mention about when talking about memory leaks.

I wanted to start the series with the difference between delete and null since it causes a huge confusion among developers and not many articles state which is better.

Delete explained

delete command is used to delete properties of an object not to delete the actual object from memory. How Garbage Collection works is that it run at certain points in time (I am not going to elaborate on that just yet) and removes all the objects from memory that has no longer referenced by anybody. By using delete command we are marking objects to be cleared on the next run of the Garbage collection (GC). This sounds good right? Do you see a problem yet? I doubt that you are. What happens if there are multiple variables referencing the same object? Is delete on a single variable free the object? The answer is NO, it will not. It will just remove the linkage between that variable and the object it is in relation with and in the best case the memory used by the variable will get cleared by GC not the object itself.

Another problem with delete is over complicated process of how and when properties can be deleted depending on which scope they are in and how they have been instantiated. Based on these combinations properties maybe set with a **DontDelete **flag that prevents them from being deleted. Adding to this the different implementation of JavaScript in Internet Explorer, you will have yourself nice exceptions coming out of nowhere.

At this point I suggest you read [2] from references to understand delete more.

Null explained

On the other hand setting a variable to null makes sure to break any references to objects in all browsers including circular references being made between the DOM elements and Javascript scopes.

Conclusion

Therefore I suggest to set variables to null rather than using delete command.

References

  1. http://onoffswitch.net/tech-talk-javascript-memory-leaks-and-jswiz/
  2. http://perfectionkills.com/understanding-delete/
  3. http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#delete