Monday, June 9, 2008

Client side Memory Leaks IE and GWT - A practical guide

By now I guess that you read the previous post and you are eager to get some practical knowledge.
So I will summarize my knowledge regarding this issue. While I agree it is a bit shallow it is much better than nothing at all.
Tools like IESieve and IEdrip proven to be inefficient when coming to GWT leaks the code is too big for them and the transformation from Java to JS complicates things.
I will be more that delighted to be proven an idiot, if someone have a better (proven) approach please let me know.

Code Review
When coming to solve /prevent memory leaks the best way will always be code review. Hence I will give a list of guidelines for reviewing GWT code:
First list of guidelines Stating the obvious:
  1. Avoid writing JSNI code. Google made quite a good job in writing "almost" leak free it is so easy to ruin it if you do not know what you are doing. Remember every JSNI code you write will lower your productivity.
  2. Do not use the DOM.* methods (except the setStyle... which are safe) . Manipulating the DOM yourself will lead you directly toward a memory leak.
Second list of guidelines - less obvious
  1. Static variables containing(even indirectly) references to widgets and dom objects may cause a leak.
  2. According to Google it should not happen :-) but in some cases event listeners may leak. unregistered them when window unloads.

Lion in the desert approach
When code review by it self is insufficient, the desperate developer should try the following approach. As stated in the previous post when a memory leak in GWT occur the entire JavaScript is locked in the memory. This will lead to a huge memory leak (megabytes in large modules). This major drawback which forces us to deal with memory leaks is also our savior. Since the memory leak is so evident it is possible to defferentiate between cases where it is existant and cases where it is eliminated. Track the VM size of the IE process while refreshing the page for several times. If the VM size inceases dramatically you have got a memory leak. Vice versa, memory do not increase constantly memory leak is solved.
Saying that all you need to do is comment out pieces of code until memory leak is eliminated.

This process is not easy nor fun some tips to improve its effectiveness:
  • Memory leaks are ilusive sometimes removing an irellevant piece of code will stop the memroy leak. As a result you should try to reach to the smallest peice of code which is still leaking before eliminating it. This will ensure you do not shoot at the wrong target .
  • Work directly on javascript files. It takes some experitse to be able to understand what you are doing but it worth it. GWT comiplation phase is long and working directly on the JS file shortens the search cycle dramatically.

Thats all folks :-)

No comments: