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.
Cost? About 2.78 microseconds per function call.
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.
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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With