Richard
Richard

Reputation: 5089

Cost of calling a function or not in Javascript

Compare:

if (myVariable) {
    doSomething()
}

function doSomething ()
{
    // Work goes here
}

vs

doSomething();

function doSomething()
{
    if (myVariable) {
        // Work goes here
    }
}

ie My question is whether it's faster to do the check outside of the function and avoid a context switch (I think that's the right term) ) or just do it inside the function because it makes such a minor difference?

Cheers.

Upvotes: 23

Views: 6233

Answers (4)

spraff
spraff

Reputation: 33395

It Just Doesn't Matter (although the first method avoids some work so it should faster, but by an amount which is probably less than statistical noise).

What really matters is which method best represents the logic. Rule of thumb is that every statement in a function should be on about the same level of abstraction. Is the conditional expression more or less abstract than the function call?

Upvotes: 16

Jeffrey Sweeney
Jeffrey Sweeney

Reputation: 6116

It's negligible; the differences in performance are miniscule, and browsers seem to handle this differently:

Edit: There is indeed a difference in performance: most browsers execute Method 1 slightly quicker.

//Method 1:

var t1 = Date.now();

myVariable = true;

for(var i = 0; i < 20000000; i++) {



    function doSomething ()
    {
        Math.sin(Math.cos(0));
    }

    if (myVariable) {
        doSomething()
    }

    myVariable = !myVariable;
}

console.log(Date.now() - t1);







//Method 2:

var t1 = Date.now();

myVariable = true;

for(var i = 0; i < 20000000; i++) {

    function doSomething()
    {
        if (myVariable) {
            Math.sin(Math.cos(0));
        }
    }


    doSomething();

    myVariable = !myVariable;

}

console.log(Date.now() - t1);





//Results:
//Safari:   About the same, former was slightly quicker
//Firefox:  Former was quicker
//Chrome:   About the same, latter was somewhat quicker
//Opera:    Executed the former quicker

Upvotes: 1

Mike Thomsen
Mike Thomsen

Reputation: 37506

It would be faster to do it outside because making a function call every time will be slightly slower than checking first and then calling the function.

But why bother? No one is going to notice a function call vs what the function call is actually doing. Inefficient DOM selectors that make your code have to hunt and peck through a huge tree structure for a few needles in the haystack are a far greater threat to performance.

Upvotes: 1

Aru S
Aru S

Reputation: 1529

I find that the second method makes for more maintainable and readable code. This incurs very little overhead.

Upvotes: 0

Related Questions