My first snippet:
public bool isSmall(int x)
{
if (x == 0)
{
return true;
}
else
{
if (x < Smallest)
{
return true;
}
else
{
return false;
}
}
}
My second snippet:
public bool isSmall(int x)
{
if (x == 0)
{
return true;
}
if (x < Smallest)
{
return true;
}
return false;
}
What I want is if (x == 0) to just return true, if not do another comparison, if (x < Smallest), and if true return true, otherwise return false.
I know my fist and second code do the same thing, but I am wondering which way to write it is better, affection, and safe? do they have any real differences? Or is it just two ways to write it?
The compiler will probably optimize either one of your routines to the following:
public bool IsSmall(int x)
{
return (x == 0 || x < Smallest);
}
To see why, write out & fill in a Boolean truth table for each set of methods.
They do the same thing. The second one could be slightly more efficient if the code was compiled directly as written (since there is one less branch statement because of the omitted else). However, all modern compilers will optimize this so that they are exactly the same.
To answer your question (which is better), whichever is easier for you to read and understand is better since they do the same thing.
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