Saturday, December 22, 2007

AJAX Memory Leaks

Memory Leaks == Memory that is allocated but never freed..

After thousands of operations with a minor leak, a significant amount of memory can be lost, resulting in slowdowns and crashes. This is the sort of thing that you usually don't have to worry about with JavaScript, but if you're writing something complex—like a video game, or a GMail—it becomes a concern.

Is it a leak caused by browsers bad design or a leak caused by the bad design of our AJAX applications?

JavaScript VM comes with a garbage collector and aside from some edge cases you might encounter, it does a pretty good job. Once you close a page a lot of work is done behind the scene to clear unreferenced objects.

Well… AJAX can mess this up. The page is not closed any more.

The problem is not AJAX in itself as a programming paradigm but in what it can do for the application. With AJAX you can retrieve data from the server without closing the page and rebuilding it. And that data is placed inside the same page and manipulated by JavaScript programs. New DOM objects are created over and over, new JavaScript objects are created based on those data, new events are attached to all this objects. Few programmers destroy those object and unattach the events.

AJAX is still young and most of the people that have done some AJAX implementation for their site are just pulling some HTML parts from the server and using innerHTML to replace the content of a div element. No harm done. As the applications are becoming more and more complex the use case changes. XML or JSON is pulled from the server and DOM objects are created based on them. It is very easy to forget something.

Unfortunately most JavaScript programmers were taught to be that way by the old browsing habits. There was no need to clean after you. When the page needed some more information, it was regenerated on the server and rendered again by the browser. A clean sheet to work on. Everything that was persistent were the cookies on the browser.

Taking care of your things in JavaScript is harder than you think. Very good programmers missed this. I was using an AJAX application from a well known company (not here to throw the stone) and after heavy usage for about two days without closing my browser, it reached the respected 500 MB in my laptop’s memory.

There are no examples,
only good practices.

More info:
* DHTML Leaks Like a Sieve
* Javascript Memory Leaks

<? adjuster ?>
Send me an email

No comments:

Post a Comment