Memory Leak In Google Analytics – Blame Canada?

Here’s an interesting post by Josh Breckman, titled “Google, you should know better. I fixed your memory leak for you.”. As it turns out, the Google Analytics code will create a new object of their analytics model on every page load of a site that uses the analytics software.

That object is used to collect user statistics, and show those nice graphs in your Google Analytics reports. But here’s the issue; the object is created on every pageload, but it’s never cleaned up properly. This means, that if you open up 1 000 sites that have Google Analytisc, that object will have been created a 1 000 times.

This appears to be the part of the code where it all goes wrong, at the A.onload bit.

if (0 == z || 2 == z) {
    var A = new Image(1, 1);
    A.src = h.Da + l;
    var p = 2 == z ?
    function() {}: x ||
    function() {};
    A.onload = p
}

It can be solved by extending the code, to include the following extra.

if (0 == z || 2 == z) {
    var A = new Image(1, 1);
    A.src = h.Da + l;
    A.onload = function() 
        { 
            A.onload = null;
            if ((z != 2) && (x != null)) 
                x(); 
        };
}

All credits go to Josh Breckman for this discovery – it’s a very interesting find.