Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1411670 Posts in 69397 Topics- by 58452 Members - Latest Member: homina

May 16, 2024, 12:02:03 PM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)best practice if statements
Pages: [1] 2 3 ... 5
Print
Author Topic: best practice if statements  (Read 15992 times)
nikki
Level 10
*****


View Profile
« on: January 21, 2010, 07:04:56 AM »


Hi

a simple question i hope:

If you have alot of if statements
which is better

Code:
if a=1 or a=2 or a=3 or a=4 or a=5
 b=10
endif

or

Code:
if a=1
 b=10
elseif a=2
 b=10
elseif a=3
 b=10
elseif etc.





the endresult is the same, but i imagine the first one to be a little bit slower , because the program has to check all the  or statements , whereas the second one stops after it has found the right statement.

anybody out here knows the best practice ?

Logged
Hajo
Level 5
*****

Dream Mechanic


View Profile
« Reply #1 on: January 21, 2010, 07:10:38 AM »

the endresult is the same, but i imagine the first one to be a little bit slower , because the program has to check all the  or statements , whereas the second one stops after it has found the right statement.

anybody out here knows the best practice ?

First one is better.

a) More readable
b) Some langauges (C, C++, Java, mabe more of the relatives) have "short circuit" evaluation.
 
-> Once one element of an "or" chain is true, it stops evaluating the rest.

Similar once one element of an "and" chain is false it stops, too.

Thus it's safe to write this for pointers:

Code:
if(p != 0 && p->something == 15)

Particularly if p is a NULL pointer some of the time.

Edit: I don't know if the language in question has short circuit evaluation. I still advice (a) for the better readability - there it is clear that all cases have the same result. An if-else chain makes me think the different branches are supposed to be distinct.
« Last Edit: January 21, 2010, 07:13:55 AM by Hajo » Logged

Per aspera ad astra
nikki
Level 10
*****


View Profile
« Reply #2 on: January 21, 2010, 07:12:22 AM »

glad to know, cause it's alot cleaner too !
could've imagined this
Quote
-> Once one element of an "or" chain is true, it stops evaluating the rest.

thanks
Logged
powly
Level 4
****



View Profile WWW
« Reply #3 on: January 21, 2010, 07:13:36 AM »

Code:
if a>=1 or a<=5
    b = 10
endif

:>

Seriously, though, ORing them together is better code (no repetition, seems more logical) and you're not very likely going to get speed problems from if statements. Switch would also work. (switch(a){case 1:case 2: case 3: case 4: case 5: {b=10;break;} default: {break;}})

Also, I'd think most compilers optimize it to quit the checks after one is true anyways.
Logged
J. Kyle Pittman
Level 6
*


PostCount++;


View Profile WWW
« Reply #4 on: January 21, 2010, 08:15:36 AM »

the endresult is the same, but i imagine the first one to be a little bit slower , because the program has to check all the  or statements , whereas the second one stops after it has found the right statement.
Most languages will stop evaluating the expression as soon as possible.  So if you have a series of ORs, and the first one evaluates to TRUE, the rest of them will be ignored.  So in this case, there would be no extra cost to putting them all in a series of ORs.

It's also important to understand that languages do this, because you never want to write something like this:

if some_condition or some_crucial_function_call()

because that crucial function call will be ignored if the first condition evaluates to TRUE.
Logged

gimymblert
Level 10
*****


The archivest master, leader of all documents


View Profile
« Reply #5 on: January 21, 2010, 08:29:38 AM »

the endresult is the same, but i imagine the first one to be a little bit slower , because the program has to check all the  or statements , whereas the second one stops after it has found the right statement.
Most languages will stop evaluating the expression as soon as possible.  So if you have a series of ORs, and the first one evaluates to TRUE, the rest of them will be ignored.  So in this case, there would be no extra cost to putting them all in a series of ORs.

It's also important to understand that languages do this, because you never want to write something like this:

if some_condition or some_crucial_function_call()

because that crucial function call will be ignored if the first condition evaluates to TRUE.

I don't understand it, if it's an OR being crucial does not count because whatever is true the code will be executed  Undecided even if crucial is false
no?
Logged

brog
Level 7
**



View Profile WWW
« Reply #6 on: January 21, 2010, 08:35:07 AM »

It's also important to understand that languages do this, because you never want to write something like this:

if some_condition or some_crucial_function_call()

I wouldn't say never; sometimes you want this behaviour, and it can be cleaner to write it like this.  But you are sacrificing clarity.
Logged
Alex May
...is probably drunk right now.
Level 10
*


hen hao wan


View Profile WWW
« Reply #7 on: January 21, 2010, 09:29:06 AM »

Write pretty much everything readable first. Then, if your performance analysis reveals the routine to be called frequently enough to warrant optimisation, optimise it.
Logged

Richard Kain
Level 10
*****



View Profile WWW
« Reply #8 on: January 21, 2010, 09:36:44 AM »

Actually, for the kind of code you're describing, a "Switch" statement would be more efficient.
Code:
switch(value_to_test)
{
    case a:
        break;
    case b:
        break;
    case c:
        break;
    default:
}
Logged
Skofo
Level 10
*****



View Profile
« Reply #9 on: January 21, 2010, 11:15:16 AM »

No it would not, since the result is always the same. if (a>=1 && a<=5) b=10; is the way to go.
« Last Edit: January 21, 2010, 11:24:06 AM by Skofo » Logged

If you wish to make a video game from scratch, you must first invent the universe.
bateleur
Level 10
*****



View Profile
« Reply #10 on: January 21, 2010, 12:23:26 PM »

The other thing which is sometimes a factor if you're really serious about optimising performance is avoiding jumps. This is for various reasons, but primarily because modern processors are highly pipelined so jumps can be slow because they invalidate the contents of the pipeline.

As such, putting all the logic into the condition of a single if statement is better than a big chain because it creates more cases in which execution involves no jumps.

All that said, it is very rare to be writing code which needs this level of optimisation. Usually, clarity is the number one priority.
Logged

nikki
Level 10
*****


View Profile
« Reply #11 on: January 21, 2010, 12:26:33 PM »

the original code was only an example offcourse, but it worked in the sense that i now understand more !

but you are completely right skofo that is the most efficient piece of code, msqrt beat you already to it though Smiley
Logged
Skofo
Level 10
*****



View Profile
« Reply #12 on: January 21, 2010, 02:11:17 PM »

But his code is incorrect!  Cry
Logged

If you wish to make a video game from scratch, you must first invent the universe.
Core Xii
Level 10
*****


the resident dissident


View Profile WWW
« Reply #13 on: January 21, 2010, 06:18:09 PM »

What about b = (a >= 1 && a <= 5 ? 10 : b); ?
Logged
Skofo
Level 10
*****



View Profile
« Reply #14 on: January 21, 2010, 09:37:18 PM »

What about b = (a >= 1 && a <= 5 ? 10 : b); ?

Oh shit, I think we may have a winner.

OH WAIT NO b=a>0&a<6?10:b; OHOHO! (Works in JavaScript, at least.)
Logged

If you wish to make a video game from scratch, you must first invent the universe.
Parthon
Level 1
*


View Profile
« Reply #15 on: January 21, 2010, 09:39:12 PM »

What if it's not 1-6 and 10, but an arbitrary set of numbers?
Logged
Zaratustra
Level 7
**



View Profile WWW
« Reply #16 on: January 21, 2010, 09:42:58 PM »

What about b = (a >= 1 && a <= 5 ? 10 : b); ?

That will almost certainly screw up. ?: has some bizarre priority.

Try b = ((a >= 1 && a <= 5) ? 10 : b);
Logged

Average Software
Level 10
*****

Fleeing all W'rkncacnter


View Profile WWW
« Reply #17 on: January 21, 2010, 09:55:36 PM »

What about b = (a >= 1 && a <= 5 ? 10 : b); ?

That will almost certainly screw up. ?: has some bizarre priority.

Try b = ((a >= 1 && a <= 5) ? 10 : b);


I wish people would just look up the precedence and not sprinkle useless parentheses all over the place.

?: out prioritizes the assignment operators and the comma operator, nothing else.

Code:
b = a >= 1 && a <= 5 ? 10 : b;

Of course, all of this is predicated on the assumption that ?: exists in whatever language he's using.  I like this better:

Code:
if A in 1 .. 5 then
    B := 10;
end if;
Logged



What would John Carmack do?
Nitro Crate
Level 3
***



View Profile
« Reply #18 on: January 21, 2010, 10:20:36 PM »

For some reason I had a sudden urge to go learn bitwise operations just for this thread so I can beat you all.

Anyways: I win.

Code:
b = b + 10 - ((((int)((((a - 1) << 1) >>> 1) + 3) & -65528) - 3) % 2 + 1) * 5;
or
Code:
b += 10 - ((((int)((((a - 1) << 1) >>> 1) + 3) & -65528) - 3) % 2 + 1) * 5;

No comparisons necessary.
Works with ints.
This is a java implementation.

Edit: wait there might be an error...
Edit2: nvm just forgot to copy paste some stuff

Edit3: LOL i just realized this doesn't even work.
I only tested it from the numbers -1 through 9
At higher numbers it messes up.
I will figure out a way to fix this!
« Last Edit: January 22, 2010, 01:51:41 PM by Nitro Crate » Logged
nikki
Level 10
*****


View Profile
« Reply #19 on: January 22, 2010, 03:34:23 AM »

i love that bitwise way :

but i'm even more in love with the readable way i would write it in blitzmax
Code:
if (a>=1 and a<=5) then b=10


btw wouldn't those modulus and multiplication things be heavier then a if ?, it looks real nerdy though so thats kewl.

Logged
Pages: [1] 2 3 ... 5
Print
Jump to:  

Theme orange-lt created by panic