473,383 Members | 1,868 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Optimization of if

Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's

How do i Optimize this? Please give me some suggestions.

Feb 1 '07 #1
37 1511
Rajen wrote:
Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's

How do i Optimize this? Please give me some suggestions.
Optimise? What's to optimise? I didn't see anything non-optimal
with the first one. (There's a missing case for when none of
X, Y, and Z are true.) The second form seems to assume that
neither `retVal1` nor `retVal2` are 0. Maybe that's true but
it seems to be asking for trouble to rely on it. And that second
form is clumsier and harder to understand.

Myself I prefer the form:

return
X ? retVal1
: Y ? retVal2
: Z ? retVal3
: whateverYouWantForNoneOfXYZ
;

laid out in whatever way fits your coding style.

Optimisation? This is really the bottleneck in your code? Colour
me gobsmacked.

--
Chris "green/purple hedgehog" Dollin
"We live for the One, you die for the One." Unsaid /Babylon 5/.

Feb 1 '07 #2
In article <11*********************@a75g2000cwd.googlegroups. com>,
Rajen <ra*****@gmail.comwrote:
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's
Your first form is much clearer, so use that. If your employer insists on
less clear code to satisfy some rules, find another employer.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 1 '07 #3
Rajen wrote:
Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's

How do i Optimize this? Please give me some suggestions.
First, it's extremely unlikely that any optimization
is needed.

Second, learn about the `else' keyword.

--
Eric Sosman
es*****@acm-dot-org.invalid
Feb 1 '07 #4
Rajen wrote:
Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
which has only one exit point. But it has more If's

How do i Optimize this? Please give me some suggestions.
Nothing says the first case generate more than one exit point of your
function. BTW some compilers will effectively generate only one exit
point and jump to it from each return point, so it far from obvious that
first case will not be optimal. Clarity is much more important than
implementation dependant low-level assumption.

a+, ld.
Feb 1 '07 #5
Laurent Deniau wrote:
Rajen wrote:
>Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
>which has only one exit point. But it has more If's

How do i Optimize this? Please give me some suggestions.

Nothing says the first case generate more than one exit point of your
function.
There are three exit points show: each return is an exit point.
(It doesn't matter how the compiler compiles it [1]; I suspect
the OP is afflicted by Code Style Rules that values Conformance
over Clarity.)

[1] EG the compiler [2] might translate `return 0;`, `return 1;`
and `return -1;` to jumps into the implementation library
code to load the constant and then return. One might then
say there were /no/ exit points in a function with those
return values ...

[2] OK, it was an RTL/2 compiler, not a C compiler, optimising
for space.

--
Chris "electric hedgehog" Dollin
There' no hortage of vowel on Uenet.

Feb 1 '07 #6
"Rajen" <ra*****@gmail.comwrote:
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}

The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's

How do i Optimize this? Please give me some suggestions.
As others have noted, you're missing a default value.

Try this:

retval=default_value;
if (Z) retval=retval3;
if (Y) retval=retval2;
if (X) retval=retval1;
return retval;

Then immediately return to the first, maintainable version, but lay it
out a bit more legibly:

if(X) return retVal1;
if(Y) return retVal2;
if(Z) return retVal3;

or if you like braces:

if(X) { return retVal1; }
if(Y) { return retVal2; }
if(Z) { return retVal3; }

Richard
Feb 1 '07 #7
"Rajen" <ra*****@gmail.comwrote in message
news:11*********************@a75g2000cwd.googlegro ups.com...
Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's
You have three options for optimization.

a)First, note in your second example that this is a control flow problem.
Your problem is keeping the value of retVal from being multiply assigned.
It is more economical to do this with an else-if statement, i.e.

if (X)
retVal = retVal1;
else if (Y)
retVal = retVal2;
else
retVal = retVal3;

This suppresses the extra "0" tests and does what you want. Also, if your
possibilities are mutually exclusive and/or exhaustive, you can suppress the
final Z test.

b)Else-if has the limit that in order to get to clause N, all of the
preceding N tests must have been evaluated. If your problem is amenable to
it, try using the switch() statement.

c)Finally, in special cases where switch() can't be used, there are
sometimes relationships that let one optimize. For example, assume that I
want a fast implementation of floor(log_10(x)) up through 10,000. I could
do it like this:

if (x < 100)
{
if (x < 10)
{
}
else
{
}
}
else
{
if (x < 1000)
{
}
else
{
}
}

When the domain is "paneled", you can often build an if() construct where
the time to reach the innermost clause is related to log(N) where N is the
number of cases.

Notice that the construct above gets there in 2 tests (rather than up to
4).
--
David T. Ashley (dt*@e3ft.com)
http://www.e3ft.com (Consulting Home Page)
http://www.dtashley.com (Personal Home Page)
http://gpl.e3ft.com (GPL Publications and Projects)
Feb 1 '07 #8
Rajen wrote:
Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
[snip]
How do i Optimize this? Please give me some suggestions.

The more typical way to write this if you want to have only one return
statement is with an if-else if ladder.

int retVal = 0; /* or other default value */

if(X)
{
retVal = retVal1;
}
else if(Y)
{
retVal = retVal2;
}
else if(Z)
{
retVal = retVal3;
}

return retVal;

This method probably is about as efficient as the one with returns in
the if() statements, understanding that such things are up to the
implementation.

You could also skip the initialization of retVal and put a terminating
else that sets it to the "no hit" value, but I'd prefer the method
above. If the return value must be one of the three, then set retVal to
one of the values and use only two if()'s.


Brian

Feb 1 '07 #9
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
"Rajen" <ra*****@gmail.comwrote:
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
[...]
As others have noted, you're missing a default value.

Try this:

retval=default_value;
if (Z) retval=retval3;
if (Y) retval=retval2;
if (X) retval=retval1;
return retval;
That's likely to be (slightly) *less* efficient, since it can assign
to retval multiple times. It can also behave differently if X, Y, and
Z are expressions that depend on each other's evaluation; for example,
evaluating Y might not work if X hasn't already been evaluated.
Then immediately return to the first, maintainable version, but lay it
out a bit more legibly:

if(X) return retVal1;
if(Y) return retVal2;
if(Z) return retVal3;

or if you like braces:

if(X) { return retVal1; }
if(Y) { return retVal2; }
if(Z) { return retVal3; }
I'd probably lay it out that way if the conditions and result
expressions really were that terse, except that I always put a blank
after an "if" (it's not a function call, so it shouldn't look like
one):

if (X) return retVal1;
if (Y) return retVal2;
if (Z) return retVal3;

But in real life, everything is likely to be longer, perhaps too long
to fit on a single line. And if the conditions really were "X", "Y",
and "Z", I'd seriously consider using names that make some actual
sense.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 1 '07 #10
Chris Dollin <ch**********@hp.comwrites:
Laurent Deniau wrote:
Rajen wrote:
Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
which has only one exit point. But it has more If's

How do i Optimize this? Please give me some suggestions.
Nothing says the first case generate more than one exit point of your
function.

There are three exit points show: each return is an exit point.
(It doesn't matter how the compiler compiles it [1]; I suspect
the OP is afflicted by Code Style Rules that values Conformance
over Clarity.)
Possibly, but we don't really know that. The question was "How do i
Optimize this?", not "How do I optimize this while conforming to
certain code style rules that I haven't bothered to tell you you
about?".

There are real advantages in restricting yourself to a single exit
point, but they show up more in maintenance than in performance. For
example, if you later find that you need to perform some action before
returning a value, given the above quoted code you need to do it in
three places. If you instead save the result to a single variable,
add "else"s, and return the value of the variable at the bottom, you
can add the extra code in just one place.

Whether this means you should *always* have just one exit point is a
subject of considerable debate.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 1 '07 #11
On 1 Feb 2007 05:45:41 -0800, "Rajen" <ra*****@gmail.comwrote:
>Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's

How do i Optimize this? Please give me some suggestions.

I assume that you are asking how to optimize the clarity and
maintainability of the code rather than speed. There have been many
excellent answers. Here is a different kind of answer. :-)

int retval_index = 0;
int retval[] = {retval_default, retval1, retval2, retval3};

if (X) retval_index = 1;
else if (Y) retval_index = 2;
else if (Z) retval_index = 3;

return retval[retval_index];

Feb 1 '07 #12
Richard Tobin wrote:
Rajen <ra*****@gmail.comwrote:
> I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's

Your first form is much clearer, so use that. If your employer
insists on less clear code to satisfy some rules, find another
employer.
No, just write clearer and more compact code:

int retval;

if (X) retval = retval1;
else if (Y) retval = retval2;
else if (Z) retval = retval3;
else retval = 0;
return retval;

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Feb 2 '07 #13
Keith Thompson wrote:
> retval=default_value;
if (Z) retval=retval3;
if (Y) retval=retval2;
if (X) retval=retval1;
return retval;

That's likely to be (slightly) *less* efficient, since it can assign
to retval multiple times. It can also behave differently if X, Y, and
Z are expressions that depend on each other's evaluation; for example,
evaluating Y might not work if X hasn't already been evaluated.
Agreed. Although any compiler written within the last 15 years will just
optimize this out (provided optimization is turned on). The amount of time
even I've just spent typing this message is more time than the difference
would ever amount to in the long run.
Feb 2 '07 #14
Keith Thompson wrote:
>There are three exit points show: each return is an exit point.
(It doesn't matter how the compiler compiles it [1]; I suspect
the OP is afflicted by Code Style Rules that values Conformance
over Clarity.)

Possibly, but we don't really know that. The question was "How do i
Optimize this?", not "How do I optimize this while conforming to
certain code style rules that I haven't bothered to tell you you
about?".
About the only way I can see optimizing this cascade is if the conditions X,
Y, Z had varying levels of computational demand. Obviously, the correct
optimization is to move the most common case to the top - provided the
secondary and tertiary cases are not exception to the common case. But we
don't know the OPs conditions.

e.g. (and I know this is obvious to you Keith):

if (compute_entire_disk_space_used() 0)
return retVal2;
else if ((rand() + ((v & y) << 4)) % 78)
return retVal1;
else if (c 0)
return retVal3;

I think it's obvious which changes should be made there.
Feb 2 '07 #15
Chris Dollin wrote:
Myself I prefer the form:

return
X ? retVal1
: Y ? retVal2
: Z ? retVal3
: whateverYouWantForNoneOfXYZ
;

laid out in whatever way fits your coding style.
Do you like pain?
Feb 2 '07 #16
CBFalconer <cb********@yahoo.comwrites:
Richard Tobin wrote:
>Rajen <ra*****@gmail.comwrote:
>> I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's

Your first form is much clearer, so use that. If your employer
insists on less clear code to satisfy some rules, find another
employer.

No, just write clearer and more compact code:

int retval;

if (X) retval = retval1;
else if (Y) retval = retval2;
else if (Z) retval = retval3;
else retval = 0;
return retval;
In commercial SW, multiple statements/expressions on a line are neither
clearer nor more "compact". The layout above is horrible and totally
debugger unfriendly. The excessive whitespace breaks the flow of a code
read. the lack of indentation doesnt hilite the conditional
assignments. 0 out of 10.

Feb 2 '07 #17
Richard wrote:
> if (X) retval = retval1;
else if (Y) retval = retval2;
else if (Z) retval = retval3;
else retval = 0;
return retval;

In commercial SW, multiple statements/expressions on a line are neither
clearer nor more "compact". The layout above is horrible and totally
debugger unfriendly. The excessive whitespace breaks the flow of a code
read. the lack of indentation doesnt hilite the conditional
assignments. 0 out of 10.
Pretty common style idiom for extremely simple maintenance logic. Get used to
it. Obviously for a more complex case that is not filled with rudiment, you
will see multiple lines. I just think you're pissed off at the "style"
itself.
Feb 2 '07 #18
On Feb 1, 6:45 pm, "Rajen" <raje...@gmail.comwrote:
Hi all,
I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
<snip>
How do i Optimize this? Please give me some suggestions.
Your first code is optimized in speed as well as size. What more
optimizations do you need?

-Nishu

Feb 2 '07 #19
On Feb 1, 7:18 pm, Eric Sosman <esos...@acm-dot-org.invalidwrote:
Rajen wrote:
Hi all,
I have a code like this.
if(X)
{
return retVal1;
}
if(Y)
{
return retVal2;
}
if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}
if( retVal == 0)
{
if( Y)
retVal=retVal2;
}
if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}
return retVal;
which has only one exit point. But it has more If's
How do i Optimize this? Please give me some suggestions.

First, it's extremely unlikely that any optimization
is needed.

Second, learn about the `else' keyword.
Is 'else' keyword really necessary? What is the drawback in using only
if statements?

Thanks,
Nishu

Feb 2 '07 #20
Christopher Layne said:
Chris Dollin wrote:
>Myself I prefer the form:

return
X ? retVal1
: Y ? retVal2
: Z ? retVal3
: whateverYouWantForNoneOfXYZ
;

laid out in whatever way fits your coding style.

Do you like pain?
Why do you ask? It looks self-documenting and pain-free to me.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 2 '07 #21
Richard wrote:
CBFalconer <cb********@yahoo.comwrites:
> int retval;

if (X) retval = retval1;
else if (Y) retval = retval2;
else if (Z) retval = retval3;
else retval = 0;
return retval;

In commercial SW, multiple statements/expressions on a line are neither
clearer nor more "compact".
They look clear and more compact to /me/.
The layout above is horrible
It's spelt b e a u t i f u l.
and totally debugger unfriendly.
Never been a problem for me.
The excessive whitespace breaks the flow of a code
read.
Maybe.
the lack of indentation doesnt hilite the conditional
assignments.
Who cares?
0 out of 10.
It's the pointless variable I hate and despise.

--
Chris "electric hedgehog" Dollin
Meaning precedes definition.

Feb 2 '07 #22
Christopher Layne wrote:
Chris Dollin wrote:
>Myself I prefer the form:

return
X ? retVal1
: Y ? retVal2
: Z ? retVal3
: whateverYouWantForNoneOfXYZ
;

laid out in whatever way fits your coding style.

Do you like pain?
MYOB.

Did you have a constructive comment to offer?

--
Chris "electric hedgehog" Dollin
"No-one here is exactly what he appears." G'kar, /Babylon 5/

Feb 2 '07 #23
On Thu, 01 Feb 2007 17:37:28 -0500, CBFalconer <cb********@yahoo.com>
wrote:
>Richard Tobin wrote:
>Rajen <ra*****@gmail.comwrote:
>> I have a code like this.
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
The above if can be written like this
int retVal = 0;
if(X)
{
retVal=retVal1;
}

if( retVal == 0)
{
if( Y)
retVal=retVal2;
}

if( retVal == 0 )
{
if(Z)
retVal=retVal3;
}

return retVal;
which has only one exit point. But it has more If's

Your first form is much clearer, so use that. If your employer
insists on less clear code to satisfy some rules, find another
employer.

No, just write clearer and more compact code:

int retval;

if (X) retval = retval1;
else if (Y) retval = retval2;
else if (Z) retval = retval3;
else retval = 0;
return retval;
what says compiler about this:
return X?retval1:Y?retval2:Z?retvalz:0:0:0;
Feb 2 '07 #24
¬a\/b wrote:
what says compiler about this:
return X?retval1:Y?retval2:Z?retvalz:0:0:0;
It says it's a syntax error, and I agree with it.

--
Chris "electric hedgehog" Dollin
"Who are you? What do you want?" /Babylon 5/

Feb 2 '07 #25
On Fri, 02 Feb 2007 09:44:01 +0000, Chris Dollin <ch**********@hp.com>
wrote:
>?\/b wrote:
>what says compiler about this:
return X?retval1:Y?retval2:Z?retvalz:0:0:0;

It says it's a syntax error, and I agree with it.

and what says about:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define uns unsigned

uns fn(uns x,uns y,uns z){return x?1:y?2:z?3:0;}

int main(void)
{uns x, y, z;

srand(time(0));
x=rand(); y=rand(); z=rand();
printf("fn(%u, %u, %u)=%u\n", x, y, z, fn(x, y, z));
printf("fn(%u, %u, %u)=%u\n", 1, 0, 0, fn(1, 0, 0));
printf("fn(%u, %u, %u)=%u\n", 0, 1, 0, fn(0, 1, 0));
printf("fn(%u, %u, %u)=%u\n", 0, 0, 1, fn(0, 0, 1));
printf("fn(%u, %u, %u)=%u\n", 0, 0, 0, fn(0, 0, 0));
return 0;
}
>--
Chris "electric hedgehog" Dollin
"Who are you? What do you want?" /Babylon 5/
"return x?1:y?2:z?3:0;"
seems more clear than
"
if(x) r=1;
else if(y) r=2;
else if(z) r=3;
else r=0;
return r;
"

Feb 2 '07 #26
¬a\/b wrote:
On Fri, 02 Feb 2007 09:44:01 +0000, Chris Dollin <ch**********@hp.com>
wrote:
>>?\/b wrote:
>>what says compiler about this:
return X?retval1:Y?retval2:Z?retvalz:0:0:0;

It says it's a syntax error, and I agree with it.

and what says about:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define uns unsigned

uns fn(uns x,uns y,uns z){return x?1:y?2:z?3:0;}
It says "stupid #define `uns`.
"return x?1:y?2:z?3:0;"
seems more clear than
"
if(x) r=1;
else if(y) r=2;
else if(z) r=3;
else r=0;
return r;
"
Well, I think so too. Of course the code /I/ showed was (a) right
the first time, (b) preserved the OPs names for values, (c) exploited
whitespace, (d) carried an explicit "your layout may vary" message,
and (e) appeared yesterday.

Below you will find some whitespace you may care to use in your code,
and some dontdefines you may find useful.

Feb 2 '07 #27
Chris Dollin <ch**********@hp.comwrote:
¬a\/b wrote:
and what says about:
#define uns unsigned
It says "stupid #define `uns`.
Interesting. Mine says: "Don't reply to trolls, please."

Richard
Feb 2 '07 #28
Keith Thompson <ks***@mib.orgwrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
"Rajen" <ra*****@gmail.comwrote:
if(X)
{
return retVal1;
}
>
if(Y)
{
return retVal2;
}
>
if(Z)
{
return retVal3;
}
[...]
As others have noted, you're missing a default value.

Try this:

retval=default_value;
if (Z) retval=retval3;
if (Y) retval=retval2;
if (X) retval=retval1;
return retval;

That's likely to be (slightly) *less* efficient, since it can assign
to retval multiple times. It can also behave differently if X, Y, and
Z are expressions that depend on each other's evaluation; for example,
evaluating Y might not work if X hasn't already been evaluated.
True. But at least it does have the sacred One Return Statement, and
doesn't have the Scary else Keyword.
Then immediately return to the first, maintainable version, but lay it
out a bit more legibly:

if(X) return retVal1;
if(Y) return retVal2;
if(Z) return retVal3;

or if you like braces:

if(X) { return retVal1; }
if(Y) { return retVal2; }
if(Z) { return retVal3; }

I'd probably lay it out that way if the conditions and result
expressions really were that terse, except that I always put a blank
after an "if" (it's not a function call, so it shouldn't look like
one):
So would I, and I did in the code above which I retyped rather than
copied-and-pasted. For the same reason as you do, BTW.
But in real life, everything is likely to be longer, perhaps too long
to fit on a single line. And if the conditions really were "X", "Y",
and "Z", I'd seriously consider using names that make some actual
sense.
They'll often be longer, but not always. I've not infrequently had code
where the conditions were something like

if (x<0) x=0;
if (y<0) y=0;
if (x>size) x=size;
if (y>size) y=size;

In context, those x and y did make sense: they were cartesian
coordinates. Possibly they were start_x and start_y, plus end_x and
end_y.

Richard
Feb 2 '07 #29
Richard wrote:
CBFalconer <cb********@yahoo.comwrites:
.... snip ...
>>
No, just write clearer and more compact code:

int retval;

if (X) retval = retval1;
else if (Y) retval = retval2;
else if (Z) retval = retval3;
else retval = 0;
return retval;

In commercial SW, multiple statements/expressions on a line are
neither clearer nor more "compact". The layout above is horrible
and totally debugger unfriendly. The excessive whitespace breaks
the flow of a code read. the lack of indentation doesnt hilite
the conditional assignments. 0 out of 10.
If you have to use a debugger on the above snippet, there is
something seriously wrong with your reading comprehension. You are
obviously a slave to poorly thought out so called 'coding
standards'.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 2 '07 #30
On Fri, 02 Feb 2007 11:14, Chris Dollin <ch**********@hp.comwrote:

no; the only error the code i posted seems to not include <time.h>
>Below you will find some whitespace you may care to use in your code,
and some dontdefines you may find useful.

.
.
.
.
.
.
.
.

#dontdefine uns
better u32? better i32?
why not?
>#dontdefine f
#dontdefine u
is it not good define "f" and "u" because there is some relation in
language constant like to write "a=282u;" or "b=878.8f;"?
(what is wrong? "8u" is a word and not 2 words so #define should not
apply there)
>#dontdefine r
#dontdefine w
#dontdefine ll
#dontdefine p
don't know why all others are not ok ( in the case these defines are
in all sources the same defines)
Feb 2 '07 #31
On Feb 1, 11:12 pm, Christopher Layne <cla...@com.anodizedwrote:
Richard wrote:
if (X) retval = retval1;
else if (Y) retval = retval2;
else if (Z) retval = retval3;
else retval = 0;
return retval;
In commercial SW, multiple statements/expressions on a line are neither
clearer nor more "compact". The layout above is horrible and totally
debugger unfriendly. The excessive whitespace breaks the flow of a code
read. the lack of indentation doesnt hilite the conditional
assignments. 0 out of 10.

Pretty common style idiom for extremely simple maintenance logic. Get used to
it. Obviously for a more complex case that is not filled with rudiment, you
will see multiple lines. I just think you're pissed off at the "style"
itself.
I wouldn't inflict the above on my maintenance programmers,
particularly if X, Y and Z are less trivial than implied. But I'd
probably only add whitespace and some sensible indenting.

The coding standard of my present employer requires braces on all
conditional blocks and loops (thankfully not switch cases as well).
There are rational reasons for this requirement, so I grit my teeth
and follow it. I pick my fights more carefully. I'm even getting the
C++ guys to use PC-lint now. And they're discovering some interesting
things about their code...

Regards,
-=Dave

Feb 2 '07 #32
Rajen:

if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
<snip>
How do i Optimize this? Please give me some suggestions.

Put the one which is most likely to be true first. Failing that, I think your
code is at optimal efficiency.

--
~/JB\~
Feb 7 '07 #33
Christopher Layne wrote:
Chris Dollin wrote:
>Myself I prefer the form:

return
X ? retVal1
: Y ? retVal2
: Z ? retVal3
: whateverYouWantForNoneOfXYZ
;

laid out in whatever way fits your coding style.

Do you like pain?
Alright, old article, but I just couldn't resist. I know some of you will get
a kick out of this:

http://thedailywtf.com/Articles/Turn...to_Eleven.aspx
Feb 12 '07 #34
Jamie Boy wrote:
>
Rajen:
if(X)
{
return retVal1;
}

if(Y)
{
return retVal2;
}

if(Z)
{
return retVal3;
}
<snip>
How do i Optimize this? Please give me some suggestions.

Put the one which is most likely to be true first. ...
That can change the behaviour if more than one of X, Y, Z is true and
retVal1, retVal2, retVal3 are different.

--
DPS
Feb 12 '07 #35
Dietmar Schindler wrote:
That can change the behaviour if more than one of X, Y, Z is true and
retVal1, retVal2, retVal3 are different.
Excepting *exceptions*, the most common case should go first. The goal is to
get a hit asap.
Feb 12 '07 #36
Christopher Layne <cl****@com.anodizedwrites:
Dietmar Schindler wrote:
>That can change the behaviour if more than one of X, Y, Z is true and
retVal1, retVal2, retVal3 are different.

Excepting *exceptions*, the most common case should go first. The goal is to
get a hit asap.
That's *a* goal, but it doesn't make a whole lot of sense to optimize
the performance of your code at the cost of breaking its semantics
(unless you just want to get your wrong answers as quickly as
possible).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 12 '07 #37
Keith Thompson wrote:
Christopher Layne <cl****@com.anodizedwrites:
>Dietmar Schindler wrote:
>>That can change the behaviour if more than one of X, Y, Z is true and
retVal1, retVal2, retVal3 are different.

Excepting *exceptions*, the most common case should go first. The goal is
to get a hit asap.

That's *a* goal, but it doesn't make a whole lot of sense to optimize
the performance of your code at the cost of breaking its semantics
(unless you just want to get your wrong answers as quickly as
possible).
That's where the "exceptions" part came in.

e.g.

if (k 40) return 2;
else if (k == 45) return 3; /* exception to above */

^^ NOT what I recommend.
Feb 13 '07 #38

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Alex Vinokur | last post by:
For instance, we need to measure performance of assignment 'ch1 = ch2' where ch1 and ch2 are of char type. We need to do that for different optimization levels of the same compiler. Here is...
9
by: Rune | last post by:
Is it best to use double quotes and let PHP expand variables inside strings, or is it faster to do the string manipulation yourself manually? Which is quicker? 1) $insert = 'To Be';...
5
by: AC Slater | last post by:
Whats the simplest way to change a single stored procedures query optimization level? In UDB8 that is. /F
2
by: Eugene | last post by:
I am trying to set query optimization class in a simple SQL UDF like this: CREATE FUNCTION udftest ( in_item_id INT ) SPECIFIC udftest MODIFIES SQL DATA RETURNS TABLE( location_id INT,...
12
by: WantedToBeDBA | last post by:
Hi all, db2 => create table emp(empno int not null primary key, \ db2 (cont.) => sex char(1) not null constraint s_check check \ db2 (cont.) => (sex in ('m','f')) \ db2 (cont.) => not enforced...
24
by: Kunal | last post by:
Hello, I need help in removing if ..else conditions inside for loops. I have used the following method but I am not sure whether it has actually helped. Below is an example to illustrate what I...
21
by: mjbackues at yahoo | last post by:
Hello. I'm having a problem with the Visual Studio .net (2003) C++ speed optimization, and hope someone can suggest a workaround. My project includes many C++ files, most of which work fine...
5
by: wkaras | last post by:
I've compiled this code: const int x0 = 10; const int x1 = 20; const int x2 = 30; int x = { x2, x0, x1 }; struct Y {
2
by: db2admin | last post by:
hi, I have query which runs great when optimization level is changed to 3 but does not run fine with default optimization level of 5. since this is a query in java code, i do not know how can i...
20
by: Ravikiran | last post by:
Hi Friends, I wanted know about whatt is ment by zero optimization and sign optimization and its differences.... Thank you...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.