Skip to content

Loading…

Prefer literal function declaration to function expression for performance reasons #217

Closed
iirelu opened this Issue · 3 comments

2 participants

@iirelu

As shown by this jsperf here, function declaration is anywhere between twice as fast and hundreds of times faster than assigning an anonymous function to a variable. Searching through the code reveals that function expressions are used predominantly (~314 times) whilst function declaration is only used 10 times.

@iirelu

I agree that it's a micro-optimisation, but it also works to improve general quality of code. However, this is an opinionated style point.

@gorhill

There is not even a micro-optimisation. The original benchmark is completely flawed. Here is the generated code by the benchmark:

while (i14100320934181105--) {
    function X() {
        return "hello";
    }
    function Y() {
        return X();
    }
    function Z() {
        return Y();
    }
    Z();
}

Which is equivalent to:

function X() {
    return "hello";
}
function Y() {
    return X();
}
function Z() {
    return Y();
}
while (i14100320934181105--) {
    Z();
}

Because of hoisting, the functions are defined once by the benchmark. Function expressions do not benefit from hoisting. Nowhere in uBlock are functions defined in a loop as above, so there is no benefit from converting function declarations to function expressions.

In general I have come to prefer function expressions, because there is no surprise through hoisting: where the declaration appear is where they start to exist.

@iirelu iirelu closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.