Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

DarkBASIC Discussion / "Nesting" IF statements?

Author
Message
Kiaurutis
13
Years of Service
User Offline
Joined: 19th Jan 2011
Location: Lithuania
Posted: 16th Jul 2011 17:12
I have some if's that have lots of conditions. The thing is that they can be placed in one if or in several if's. What is better?



IMO:
Several IF's are better when "a" is false so others aren't checked
One IF looks not so spaghetti

Waiting for Your opinion

Join The dark Side! We have cookies
Libervurto
17
Years of Service
User Offline
Joined: 30th Jun 2006
Location: On Toast
Posted: 16th Jul 2011 17:50 Edited at: 16th Jul 2011 17:51
As with most programming decisions, it depends on the circumstances.
If we wanted to check if a co-ordinate was within a 2D area, using one line might look better.

But if we had more complex conditions it could get very difficult to read.
I would tend to say that it's best to use as few IF's as possible but without involving too many different variables and making it too complicated. So I might write the 2D area check as:

By separating the X and Y axes we've made it a bit easier to follow. It really is down to personal preference though.

Kiaurutis
13
Years of Service
User Offline
Joined: 19th Jan 2011
Location: Lithuania
Posted: 16th Jul 2011 19:38
Lets say I have 500 objects and have to check their attributes every loop. Would it be faster to check

if (x>left)
if (x<right)
if (y>top)
if (y<bottom)

than

if (x>left) and (x<right) and (y>top) and (y<bottom)?

Join The dark Side! We have cookies
Libervurto
17
Years of Service
User Offline
Joined: 30th Jun 2006
Location: On Toast
Posted: 17th Jul 2011 01:52
Nesting the IF statements will be faster because as you said, if the first condition is false the rest wont be tested. If all the conditions are on the same line they will all be tested.
In some languages, if a condition has returned a value that makes the overall condition (all the conditions added together) false it will skip the other conditions, but DB will continue until all conditions have been tested even if it is impossible for the overall condition to be true.

Kevin Picone
21
Years of Service
User Offline
Joined: 27th Aug 2002
Location: Australia
Posted: 17th Jul 2011 04:51
There's few related (but old) articles on here

* Speeding up Get Distance Examples
* Binary IF/THEN speed up Example

Login to post a reply

Server time is: 2024-04-26 20:01:18
Your offset time is: 2024-04-26 20:01:18