Reputation: 6291
Which of the following approaches is more efficient and faster
Nested conditions
if( a == b ) {
if( b1 == c ) {
if( c1 == d ) {
}
}
}
Logical expressions
if( a==b && b1 == c && c1 == d) {
}
Generally which of the above approaches is faster and why? Which one should be preffered when writing libraries? I know that in the first approach,one block is executed only if the upper if statement results in true.. In the second approach ,as the condition evaluation is from left to right,it will also skip the next conditions ,if previous conditions are false..Am I right?
If so is there any performance difference between the two approaches?
Upvotes: 1
Views: 990
Reputation: 1074335
I doubt there would be any significant performance difference between them because as you suspected, &&
and ||
short-circuit in JavaScript (so the b == c
won't be done if a == b
is false and &&
is used) and JavaScript doesn't have to do any particular plumbing for entering the block (as it doesn't have block-scope variables, yet).
But these things vary from implementation to implementation, the only way to really know is to test on your target engines, perhaps with a site like http://jsperf.com if targeting browsers.
The more important question is: Does it matter? As opposed to readability, maintainability, etc. I'd say readability/maintainability/clarity would trump any potential performance savings by a huge margin.
Also note that if you're really into this stuff, you probably want to be using something like the Closure Compiler in advanced mode anyway, which will do actual optimizations on the code (it's not just a minifier).
Upvotes: 5