Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost of calling a function or not in Javascript

Tags:

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.

like image 407
Richard Avatar asked Jan 26 '12 14:01

Richard


People also ask

Are function calls expensive in JavaScript?

Cost? About 2.78 microseconds per function call.

Is calling a function expensive?

Speaking from personal experience, I write code in a proprietary language that is fairly modern in terms of capability, but function calls are ridiculously expensive, to the point where even typical for loops have to be optimized for speed: for(Integer index = 0, size = someList.

Can I call a function in JavaScript?

The JavaScript call() MethodIt can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.


2 Answers

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?

like image 88
spraff Avatar answered Oct 22 '22 17:10

spraff


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.

like image 37
Mike Thomsen Avatar answered Oct 22 '22 17:10

Mike Thomsen