Ayrton
Ayrton

Reputation: 2303

What are the performance effects of declaring functions inside functions?

Suppose I have the following classes Test1 and Test2. Test1 declares two functions, fA and fB, and fA is called inside fB. Test2 declares fA inside fB. Would either of them have a performance advantage over the other? Assume that fA is recursive and will be called once every time fB is called.

Example:

function Test1() {
    this.fA = function() {
        //function body here...
    };

    this.fB = function() {
        //some code...

        this.fA();
    };
};

function Test2() {
    this.fB = function() {
        let fA = function() {
            //function body here...
        };

        //some code...

        fA();
    };
};

Upvotes: 0

Views: 45

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49803

In the first case, fA gets created once; in the second, it gets created each time fB is called. So the second is surely slower, but as @Pointy points out, probably not enough to worry about.

Upvotes: 1

Related Questions