Rewind
Rewind

Reputation: 2814

Javascript Class - Function Optimisation (Functions Within Functions)

I am defining a class:

MyClass = function () {
    // Class member variables here
};

MyClass.prototype.MyFunction = function () {
    // Do stuff, see below
};

The thing I am not sure about is MyFunction. This is the pattern I have at the moment (a function within a function). I have it this way because it looks tidy. MyFunctionSubFunction is only asscociated with MyFunction, so from a style point of view I am assuming MyFunctionSubFunction should be within the definition of MyFunction.

MyClass.prototype.MyFunction = function () {
    var i, j, iIter, jIter, a, b, c, val;
    var MyFunctionSubFunction = function (a, b, c) {
        // Do things with a, b and c
    };

    // iIter and jIter are set to values depending on what is going on

    for(i=0; i<iIter; i++) {
        for(j=0; j<jIter; j++) {
            // a, b and c are now set depending on i and j

            MyFunctionSubFunction(a, b, c);
        }
    }
};

Is this good coding practice (the function within a function)?

Is this optimised for speed and everything else?

MyFunction (the upper function) is being called about 250 times a second (its a game, this is part of the AI code).

Or should I be doing something like this instead?:

MyClass.prototype.MyFunction = function () {
    var i, j, iIter, jIter, a, b, c, val;

    // iIter and jIter are set to values depending on what is going on

    for(i=0; i<iIter; i++) {
        for(j=0; j<jIter; j++) {
            // a, b and c are now set depending on i and j

            this.MyFunctionSubFunction(a, b, c);
        }
    }
};

MyClass.prototype.MyFunctionSubFunction = function (a, b, c) {
    // Do things with a, b and c
};

Upvotes: 0

Views: 37

Answers (1)

Artjom B.
Artjom B.

Reputation: 61902

Defining MyFunctionSubFunction inside of MyFunction incurs an overhead because every time MyFunction is called a new function called MyFunctionSubFunction is created.

If you don't want MyFunctionSubFunction to leak out, you could use an IIFE:

(function(){
    var MyFunctionSubFunction = function (a, b, c) {
        // Do things with a, b and c
    };
    MyClass.prototype.MyFunction = function () {
        // use MyFunctionSubFunction here somewhere
    };
})()

Since MyFunctionSubFunction directly operates on a, b and c, it doesn't need to be part of the MyClass.prototype. Although, it could be.

Upvotes: 1

Related Questions