KA Hearth

A small blog where Matthias posted thoughts on things happening around Khan Academy. (Archived) About Me

View the Project on GitHub

A fix for memory leaks with OOP

The issue is of course described in my earlier post.
I stumbled across a solution to this issue when looking at a recent Hot list program. It included the following code snippet at the top of the program.

Object.constructor.prototype.create = function () {
    var obj = Object.create(this.prototype);
    this.apply(obj, arguments);
    return obj;
};

Then instead of using new, one can use

AnyClass.create(params)

This allows you to bypass KA’s parsing of new and their pesky ApplyInstance code. If you’re going to be writing complex, Object Oriented code on Khan Academy, of the sort that I advised against in my previous post, I can recommend this method as a way to cut down on lag.

A short history of this code snippet*:

*If you used this earlier but didn’t end up on this list, let me know, but the above happened to be the people I saw using it. I’m sure it’s more well know than I realized and this is not meant to be a conclusive history.

The below code (which crashed in less than a minute with new), ran fine and without lag during my testing. Though the framerate seemed slightly slower than without OOP, I’m sure it’s not much worse than new would be without KA’s fiddling.

Object.constructor.prototype.create = function () {
    var obj = Object.create(this.prototype);
    return this.apply(obj, arguments), obj;
};

var obj = new PVector(width/2, height/2);

var draw = function() {
    background(255);
    ellipse(obj.x, obj.y, 10, 10);

    for (var i = 0; i < 10000; i ++) {
        obj.add(PVector.create(random(-1, 1), random(-1, 1)));
    }
};