|
nested if-statements V.S. multiple-alternative if-statements V.S. switch
08-02-2011, 07:58 PM
|
nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 680
Name: Lashtal
|
- it's preferrable to use a multiple-alternative if-statement over a nested-if as much as possible (reason: cleaner, more readable code)
- if you plan on testing n<=10 test cases, use a switch statement. (reason: most compilers better optimize switch statements, due to branch/jump table implementation, wherein this feature is not created for if-statements... and, why not?)
am I wrong? and: have you got any further improvements on my logic?
__________________
Currently Reading: Please login or register to view this content. Registration is FREE
|
|
|
|
08-02-2011, 08:51 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 919
Name: Scott Kaye
Location: Ontario
|
I personally like using nested if statements, because you can 'else' each error, for example:
PHP Code:
$a=1; $b=2; $c=3;
//Multiple if ($a==1&&$b==2&&$c==100) { //Obviously $c doesn't equal 100 echo "All correct!"; }
//Nested if ($a==1) { echo $a." is ".1; if ($b==2) { echo $b." is ".2; if ($c==100) { echo $c." is ".100; } else {echo $c." isn't ".100;} } else {echo $b." isn't ".2;} } else {echo $a." isn't ".1;}
There's a drawback for nesting them, though, and that is Priority. If $a didn't equal 1, then we'd never get to check $b or $c. So we use the third example:
PHP Code:
$a=1; $b=2; $c=3;
if ($a==1) { echo $a." is ".1; } else {echo $a " isn't".1;} if ($b==2) { echo $b." is ".2; } else {echo $b " isn't".2;} if ($c==100) { echo $c." is ".100; } else {echo $c " isn't".100;}
So we can catch each 'error' (a return false) and display them accordingly. But again, there's a drawback with THIS, and that is code usage. Why use so much code just to check if a value is a value? If x = y? We could use switch, but we'd end up with the same code in different syntax.
So really it comes down to what you need. If you're not planning on displaying any output back to the user, use multiple-arguments if statements. But if you are, then you should use individual if statements.
[/book]
|
|
|
|
08-02-2011, 08:52 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 2,815
Name: Matt
Location: Irvine, CA
|
It's difficult to give general advice on this topic because it really depends on the circumstances and the preference of the coder.
As far as the performance implications of using a switch statement as opposed to an if/elseif/else go, unless you're writing embedded software that is going to be installed on someone's pacemaker, the difference is way to insignificant to be concerned with.
If you want to optimize your code, start with the big picture. If you find that you've perfected everything to the point where all you have left to do is worry about if you should use a switch statement instead of an if, then you either missed something or need to move on to a new project.
|
|
|
|
08-02-2011, 08:57 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 919
Name: Scott Kaye
Location: Ontario
|
Quote:
Originally Posted by NullPointer
...if you should use a switch statement instead of an if...
|
[unrelated]
To me, using 'switch' looks far more technical. The stronger absence or curly braces makes you look more professional. As well, it looks cleaner, and there's less code. Example:
PHP Code:
$a=1; //If: if ($a==1) { //$a is 1 } else if ($a==2) { //$a is 2 } else { //$a is $a }
//Switch: switch ($a) { case 1: //$a is 1 break; case 2: //$a is 2 break; default: //$a is $a break; }
|
|
|
|
08-02-2011, 08:59 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 2,815
Name: Matt
Location: Irvine, CA
|
If you're using PHP you can use the alternative syntax:
PHP Code:
if($foo):
//code here
elseif($bar):
//more code here
else:
//even more code here
endif;
|
|
|
|
08-02-2011, 09:05 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 919
Name: Scott Kaye
Location: Ontario
|
Quote:
Originally Posted by NullPointer
If you're using PHP you can use the alternative syntax:
(...)
|
That's cool, NullPointer! I've never seen that before.
EDIT: Wouldn't the lack of curly braces only allow for one-liners? I saw in a tutorial that this:
PHP Code:
if (condition == true) //do something //do something 2
evaluates to this:
PHP Code:
if (condition == true) { //do something } else { //do something 2 }
I always use ternary operators for one-liners.
PHP Code:
$a=1;
//Instead of if ($a==1) { $b=2; } else { $b=null; }
//Use this: $b=$a=1?2:null;
**I'm pretty sure, untested
Last edited by Physicsguy; 08-02-2011 at 09:15 PM..
|
|
|
|
08-02-2011, 11:09 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 2,815
Name: Matt
Location: Irvine, CA
|
Quote:
Originally Posted by Physicsguy
Wouldn't the lack of curly braces only allow for one-liners?
|
If you're using the alternative syntax you use a colon to indicate the start of an if statement and endif to indicate the end, so braces aren't necessary.
|
|
|
|
08-02-2011, 11:20 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 680
Name: Lashtal
|
Quote:
Originally Posted by NullPointer
If you want to optimize your code, start with the big picture.
|
please define 'big picture'
__________________
Currently Reading: Please login or register to view this content. Registration is FREE
|
|
|
|
08-04-2011, 08:41 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 680
Name: Lashtal
|
something else i'd like to add to the use of Switch statements: switch is ideal for coding values that lie in close range to each other, (Ex. 1,2,3,10,25) as opposed to values that do not (Ex. 1, 100, 500000) as the difference between the digits in the latter example range from 1 to 100, for a difference of 99 and 500,000 to 100 for a difference of 499,900; the effect of which is that when switch generates a branch/-jump table (through your mainstream compiler) what it's actually doing is storing relational values for the numbers ranging between 1 to 100, 100 to 500 thousand and so on.
in a nutshell: Switch is ideal then for a sequence of no more than 10 values without great numerical differentiation/distance between themselves. Otherwise, use multiple-alternative if-statements as opposed to nested-ifs to maximize code readability (also known as "syntactic sugar").
this is all a bit on the nazi-side, I understand. And I think the point Nullpointer is making, though I ask 'define big picture' as a way of demonstrating the relativity of that term. If my specific interest is to understand and determine what allows for the greatest efficiency between languages and platforms, i'd have to know things like this- as well as the historical determinents for why they were used, and how they're still used today (and compare them to other comparatively similar tehnologies: in this case, programming languages)
Though I believe Null was pointing out that this kind of optimization is generally not regarded (at least to this degree) by the majority of programmers, due in large part to Moore's Law, which accounts for the rapid progress in hardware. With the possibility of quantum computers in your home by 2025, this subject may very well be on the decline and "language wars" will become (if they are not already, complete wastes of time); instead, we'll be focusing on "which has the lowest learning curve?, which has the highest product turn-around?", etc. etc.
Which is basically what's already happening today, so in that sense Null is right.
__________________
Currently Reading: Please login or register to view this content. Registration is FREE
Last edited by Lashtal; 08-04-2011 at 08:42 PM..
|
|
|
|
08-04-2011, 09:12 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 919
Name: Scott Kaye
Location: Ontario
|
That's very interesting, Lashtal. I didn't know how switch actually worked. All I care is that it does work.
About the point you made about quantum computers. I couldn't agree more, because if you think about how far we've come in 30 years. Commodore 64's had 64k of "memory", and yet we still had games and useful programs, even music for it. The drawback with more powerful computers is this graph:
Programmers will spend less time making their code GOOD and more time making it look 'purty.
|
|
|
|
08-04-2011, 10:02 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 2,815
Name: Matt
Location: Irvine, CA
|
It's not necessarily about having more performance at your disposal so you don't have to worry about it as much. There are decisions beyond which of two functionally equivalent syntaxes to use that have a greater impact on the performance of your application (which is what I meant earlier by 'big picture').
Not that the increases in performance haven't impacted the way people code. "If vs switch" is a perfect example of something you should never have to worry about (with very few exceptions) anymore because the machine your code is running on will have enough performance to spare even if you choose the slower construct.
Even if this weren't the case however, I would still say that it really doesn't matter. You'd be lucky to squeeze a 1% performance increase out of a typical application by switching from an if to a switch statement. Moreover there are circumstances where there would be no performance increase or even a decrease. Dedicating even a small amount of time to deciding which one to use is a waste given that chances are there are more important things you could be improving.
It's a good intellectual/academic exercise, but most likely not something you want to be thinking about in a real world app.
|
|
|
|
08-05-2011, 06:00 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 680
Name: Lashtal
|
I agree with you, then I simultaneously disagree with you at the same time.
Agree: this matter of "if v.s. switch" is an incredibly insignificant thing to worry about for most programmers, owing to the power of today's computers
Disagree: there is the case, (which not many people deal with, i'm sure), where you're dealing with a million lines of code (or more); and the difference between how you code an If to a Switch could improve performance by even 5% (which *could* be significant, and considered "an improvement" in comparison to a competitor product)
In Summation: we'd be opening the door to a general discussion in contrast to a more conduscive discussion, which'd no doubt be based upon Actual Case Studies of measured performance increase.
Until then, it's a rather subjective discussion and one that not many of (perhaps 94%) of today's programmers need to worry about.
an interesting comparison would be in terms of C++ coders with large-scale applications requiring conversions to Assembly in order to meet bottleneck requirements. The subjective question(s) asked would be: "how much do we need to convert to assembly?" and "which part(s) of the code base should we endeavour to optimize?"
Overall, I feel as if code-optimization is not a waste of time (though i'm sure it can be, I know it can be); but think on this: if you're creating modular code which you plan on re-using in several other projects across the board, wouldn't it make sense to optimize the efficiency of your building blocks?
the obvious answer is "yes!", 'why would I NOT want my system(s)/program(s) to be as efficient as they can possibly be?'
but in practice: the answer, which comprises how much time we should spend on this activity versus, you know; coding even more applications, or developing features for already-existent programs, is outweighed on a case-by-case/subjective basis where a factor of time (which is always money) comes into play. Where the benefits of coding more features for already-existent applications (or creating even more applications, with already-workable code) is outweighed by "how much time we should spend on code optimization?"
I think the differences in judgement as per code optimization are weighed on different levels for large-scale applications (1-3 million lines of code or more), versus the general programmer (pumping out as as many applications as possible to get as much money as possible in as short of an amount of time as possible), versus the CEO of a biz with a commercial product who also takes "the general programmer's" mind-set into play, yet elevates the importance of his product's efficiency/life-span to a higher level than I think the guy whose being paid to code it for him does.
And these are just a few (though I think the most prevalent) subjective factors.
__________________
Currently Reading: Please login or register to view this content. Registration is FREE
|
|
|
|
08-05-2011, 06:12 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 680
Name: Lashtal
|
lol, I love that graph physicsguy... it's absolutely true and I think very encouraging for us all.
Us computer programmers/enthusiasts, we're like pilgrims on a new frontier... improvements are always being made, there is NO LIMIT to what we may discover here.
We live in a very exciting time: where the prevalence and importance of computers (and the field of computing), has been elevated to a point which it has never been in the history of THE WORLD!
Richard Dawkins points out in "The God Delusion" how lucky we are to even exist. What a miracle it is that we are even here. Weigh this with the probability of the idea that our species has even made it this far... out of how many other known planets/worlds/systems also inhabit species that have made it this far? (and if I put it in perspective like that, than i'm sure you can see what i'm saying)
What a fascinating field of research, A SCIENCE! in it's infant stages... (likewise, the field of psychology is also considered to be)
humans, using computers, using humans (to effect computers)
How many people today carry a computer with them on their person? How many have access to the world wide web? How many more in the next 20 years?
The Borg will assimilate all.
__________________
Currently Reading: Please login or register to view this content. Registration is FREE
Last edited by Lashtal; 08-05-2011 at 06:16 PM..
|
|
|
|
08-05-2011, 06:53 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 807
Name: Mattias Nordahl
Location: Sweden
|
This was some interesting reading 
__________________
Your answers will only be as good as your question. Formulate it well and give all the necessary information.
|
|
|
|
08-05-2011, 07:43 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 2,815
Name: Matt
Location: Irvine, CA
|
Quote:
Originally Posted by Lashtal
Disagree: there is the case, (which not many people deal with, i'm sure), where you're dealing with a million lines of code (or more); and the difference between how you code an If to a Switch could improve performance by even 5% (which *could* be significant, and considered "an improvement" in comparison to a competitor product)
|
I'd like to see one of those cases.
Quote:
Originally Posted by Lashtal
Overall, I feel as if code-optimization is not a waste of time
|
I don't know of anyone who would argue that it is a waste of time. What is a waste of time is making bad decisions about what to optimize.
You should optimize from the top down. Look at your application as a whole, identify the critical components and bottlenecks and improve them in meaningful ways. If you find that all you can do is try to work out whether a switch or an if is faster then it is time to move on.
"Meaningful ways" isn't always (or even mostly) about performance, sometimes it's about maintainability, which can sometimes mean sacrificing clock cycles for code that will be easier and faster to work with down the line.
If vs Switch is purely a design choice. Performance is the last thing that should be on your mind, because more often than not, good design leads to good performance.
|
|
|
|
08-05-2011, 08:33 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 2,815
Name: Matt
Location: Irvine, CA
|
By the way, the overall premise that switch is faster than if is dependent on a few factors, including the language you're using. In PHP I found that if/elseif was about 25% faster than switch in this particular case (I setup the test keeping in mind that switch is supposed to be faster with many cases and if those cases are within a small range):
PHP Code:
$start = microtime(true);
for($i = 0; $i < 1000000; $i++)
{
$x = $i % 6;
if($x == 0)
{
}
elseif($x == 1)
{
}
elseif($x == 2)
{
}
elseif($x == 3)
{
}
elseif($x == 4)
{
}
elseif($x == 5)
{
}
elseif($x == 6)
{
}
elseif($x == 7)
{
}
elseif($x == 8)
{
}
elseif($x == 9)
{
}
else //5
{
}
}
echo microtime(true) - $start . "\n";
$start = microtime(true);
for($j = 0; $j < 1000000; $j++)
{
$y = $j % 10;
switch($y)
{
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
case 9:
break;
default:
}
}
echo microtime(true) - $start . "\n";
PHP is interpreted, not compiled so this may be a factor in the if statement being faster. Of course, once you start doing any significant amount of work within a particular case or if block (or any work outside of either statement) the performance difference approaches zero fairly quickly.
Last edited by NullPointer; 08-05-2011 at 08:34 PM..
|
|
|
|
08-05-2011, 08:59 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 2,815
Name: Matt
Location: Irvine, CA
|
Quote:
Originally Posted by NullPointer
Of course, once you start doing any significant amount of work within a particular case or if block (or any work outside of either statement) the performance difference approaches zero fairly quickly.
|
Just to demonstrate this point, the following code is bascially the same as the code above, but now I'm actually doing something in the body of the cases and if blocks, as well as something outside of the statement.
PHP Code:
$start = microtime(true);
for($i = 0; $i < 1000000; $i++)
{
$x = $i % 6;
$q1 = .0034;
$q2 = .0056;
$r = .5;
$bar = 8.988 * pow(10, 9) * (($q1*$q2)/pow($r, 2));
if($x == 0)
{
$foo = md5(rand(0, $i));
}
elseif($x == 1)
{
$foo = md5(rand(0, $i));
}
elseif($x == 2)
{
$foo = md5(rand(0, $i));
}
elseif($x == 3)
{
$foo = md5(rand(0, $i));
}
elseif($x == 4)
{
$foo = md5(rand(0, $i));
}
elseif($x == 5)
{
$foo = md5(rand(0, $i));
}
elseif($x == 6)
{
$foo = md5(rand(0, $i));
}
elseif($x == 7)
{
$foo = md5(rand(0, $i));
}
elseif($x == 8)
{
$foo = md5(rand(0, $i));
}
elseif($x == 9)
{
$foo = md5(rand(0, $i));
}
else //5
{
$foo = md5(rand(0, $i));
}
}
echo microtime(true) - $start . "\n";
$start = microtime(true);
for($j = 0; $j < 1000000; $j++)
{
$y = $j % 10;
$q1 = .0034;
$q2 = .0056;
$r = .5;
$bar = 8.988 * pow(10, 9) * (($q1*$q2)/pow($r, 2));
switch($y)
{
case 0:
$foo = md5(rand(0, $i));
break;
case 1:
$foo = md5(rand(0, $i));
break;
case 2:
$foo = md5(rand(0, $i));
break;
case 3:
$foo = md5(rand(0, $i));
break;
case 4:
$foo = md5(rand(0, $i));
break;
case 5:
$foo = md5(rand(0, $i));
break;
case 6:
$foo = md5(rand(0, $i));
break;
case 7:
$foo = md5(rand(0, $i));
break;
case 8:
$foo = md5(rand(0, $i));
break;
case 9:
$foo = md5(rand(0, $i));
break;
default:
$foo = md5(rand(0, $i));
}
}
echo microtime(true) - $start . "\n";
The if statement is still faster, but only by 2%.
In an actual application, where the vast majority of the work is done outside of the if/switch in question and you're actually doing something inside the blocks, I don't see how you could ever get a useful performance increase by switching from one to the other. At least not enough of an increase to justify the time you would have to spend determining which is the faster construct.
Last edited by NullPointer; 08-05-2011 at 09:01 PM..
|
|
|
|
08-05-2011, 10:02 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 680
Name: Lashtal
|
I appreciate your case studies, rather empirical. Though, as you're aware, these case studies should be tested in controlled environments. Where a particular technology is used on a particular platform, with a particular machine (whose capabilities can be measured across the board)
Basically, as replicable by other scientists/future-experimenters as possible.
---
technological advancement(?): http://www.suspekt.org/switchtable/
at least important enough for 2 people to care, lol
And that's also the beauty of this field: opportunities to explore efficiency/advancements are Practically Unbounded
__________________
Currently Reading: Please login or register to view this content. Registration is FREE
|
|
|
|
08-05-2011, 10:05 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 919
Name: Scott Kaye
Location: Ontario
|
Is there a website online to reliably test code like this, or any code at all? It would be nice to have a one-stop, go-to source for code benchmarking, where all other benchmarks would reside and be based off of.
|
|
|
|
08-05-2011, 10:17 PM
|
Re: nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
Posts: 2,815
Name: Matt
Location: Irvine, CA
|
The point wasn't to produce accurate data as to the performance of a switch statement and if statement, the point was to demonstrate that the performance difference becomes negligible when you look at it in the context of the rest of your application. You don't need a controlled environment to demonstrate that.
If it's the case that the results I got on my machine don't correspond with what other people are getting then it only serves to further my overall point: "switch statements are faster than if statements" isn't a legitimate premise to base your code optimizations on.
|
|
|
|
|
« Reply to nested if-statements V.S. multiple-alternative if-statements V.S. switch
|
|
|
| Thread Tools |
Search this Thread |
|
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|