...

View Full Version : which is better?



dswimboy
05-04-2004, 10:55 PM
if ( (test1) && (test2) ) {
code
} else {
code
}

or?


if (test1) {
if (test2) {
code
}
} else {
code
}

dswimboy
05-04-2004, 10:57 PM
responding to myself.

i understand there are specific benifits to both. if one test2 has some odd null values based on test1 or whatever. but in general.

i program in perl and php, currently, but i'd be interesting in hearing opinions from other languages as well.

Jason
05-04-2004, 11:17 PM
there might be a difference in cpu time, though Im sure your not to worried about that as it would be very small with the different checks that would have to go on. Also the readability of the code for others. Some might prefer it one way or the other. Otherwise they are the same to me...


Jason

Unit
05-05-2004, 12:55 AM
i understand there are specific benifits to both. if one test2 has some odd null values based on test1 or whatever. but in general.

This is not true. All the languages I know short circuit the second expression depending on the result of the first expression.

For example if test2 dereferences a null pointer and test1 checks for it, then the code runs fine because as soon as test1 fails, test2 is not even computed.

I am not sure about the performance concerns. I'd like to hear some opinions on that too!

shmoove
05-05-2004, 08:18 AM
The difference in performance would depend on the language. In a language like C or Java there would be no difference since if test1 is false then test2 won't be evaluated. In a language like VB (I know the code isn't VB, but this is just a for instance) both expressions in the if statement will be evaluated regardless.

But those examples aren't semantically the same: in the second example the else code won't be executed if test1 is true and test2 is false, and in the first example it will.

shmoove

daem0n
05-05-2004, 10:17 AM
This is just my opinion based on "easy to understand"

if(condition1 && condition2)
{
code
}
I apply this style when condition1 and condition2 are parallel, that's mean they are independent.

if(condition1)
{
if(condition2)
{
code
}
}
I apply this style when codition2 depend on condition1.

It is just based on 1 criterion, I have no idea about speed of execution.

liorean
05-05-2004, 10:27 AM
The nested ifs will be marginally faster, notable only when executing the else clause.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum