Okay, so I'm like anyone else... I have to do a first post and ramble a bit. Lately I've been spending a lot of time working in the JavaScript world. I know a lot of people will say "WTF?" but it's an amazing language. It's open style and simple structure allow for some powerful code to be written.
I've spent the last 6 months of my life building an application framework in JavaScript that will be the foundation of many applications. The beauty of this framework is its simplicity. At the core is the Component which is any renderable object for use in a browser. At the highest level, we have trees, grids, splitpanes and more. We can load panes dynamically and fill them on the fly. All of this is backed by Java and JSP running in an Apache/Tomcat environment. As far as we know, none of this has been done before to this extent.
The purpose of this blog is to give me some sort of outlet for all of what I've done. I need to talk about what I've found out and what I've yet to do. The end effect is to share the knowledge I have with other coders.
To start y'all off, here is something I learned along the way. Now, lemme preface this with "I hate Internet Explorer". I can't develop in that piece o' crap browser. It doesn't have robust debugging capabilities, and it's slow. So slow that it frustrates me... I develop in Firefox with the Venkman debugger. It's fast and it's powerful. Yeah, all the code we've written runs in IE, but it's begrudgingly that I even test it. Unfortunately, our customers demand it (since it owns a mere 80% of the browser market)... Anyways, on to the bit of knowledge:
In IE, there is a HUGE problem with leaky closures. Creating a JavaScript closure leads to a huge drain of memory. A closure looks like this:
function wrapIt(callback, someNumber)
{
return function() { someNumber += 1; callback.call(doThis); };
}
By doing this, you're returning a function that contains a reference to two variables passed from the outermost (containing) function. If you were to supply this to an event handler, it would leak a steady amount until IE became unresponsive. To get around this, some suggest that you free your event handlers by removing them and then setting them to null when the page unloads.
What we found was simpler... You simply write the function and pass in references to the values as opposed to creating the closure:
function wrapIt(callback, someNumber)
{
var code = "arguments.callee.someNum += 1; arguments.callee.callback.call(arguments.callee.someNum);";
var fn = new Function(code);
fn.someNum = someNumber;
fn.callback = callback;
return fn;
}
No longer do we establish a closure. Instead, we've essentially passed the values into the function by reference. Thus, the memory leak is avoided. I hope this helps someone -- it sure as hell saved me a lot of hair pulling.
- SphericalCow