last-child
last-child

Reputation: 4871

Should I avoid executing the same function declaration multiple times for performance reasons?

A powerful feature of Javascript is how you can use closures and higher order functions to hide private data:

function outerFunction(closureArgument) {
    var closureVariable = something;
    return function innerFunction() {
        // do something with the closed variables
    }
}

However, this means that every time I call outerFunction, a new innerFunction is declared and returned, which means that outerFunction(arg) !== outerFunction(arg). I wonder to what extent, if any, this might impact performance. As an example, a typical alternative would be to create a constructor that holds the data, and put innerFunction on the prototype:

function Constructor(argument) {
    this.argument = argument;
    this.variable = something;
}

Constructor.prototype.method = function() {
    // do something with this.argument and this.variable
}

In that case, there is a single function that is shared by a number of instances, e.g new Constructor().method === new Constructor().method, but the data can not easily be made private, and the function can only be called as a method, so it has access to its context variables (This is just an example; there are other ways to solve the issue; my question is not actually about constructors and prototypes).

Does this matter from a performance perspective? It seems to me that since a function is always a literal, and the function body itself is immutable, Javascript engines should be able to optimize the above code example so that there shouldn't be a big performance impact because we have "multiple" functions instead of a single, shared function.

In summary: Does running the same function declaration multiple times come with any significant performance penalty, or do Javascript engines optimize it?

Upvotes: 1

Views: 352

Answers (1)

Bergi
Bergi

Reputation: 664297

Yes, engines do optimise closures. A lot. There is no significant performance or memory penalty.

However, the prototype approach still can be faster, because engines are better at detecting the potential to inline a method call. You will want to step through the details in this article - though it could easily be outdated by newer compiler optimisations.
But don't fear closures because of that, any differences will be negligible for most cases you encounter. If in doubt, and with real need for speed, benchmark your code (and avoid premature optimisation till then). If closures make your code easier to read, write, maintain, go for them. They are a powerful tool that you don't want to miss.

Upvotes: 2

Related Questions