CodeSOD: How to avoid the expensive “If-then-else” statement
or How to know when to optimize
About two years ago, in Data Structures and Algorithms, our lecturer briefly talked about the “If-then-else” statement and how much expensive it is as an operation. Leaving us with many questions, I extensively researched the topic and found out that the word “expensive” is, well, really relative. Nevertheless, a particular student found a way to avoid the cost…
First of all, here is how much you need to worry about the cost of the “If-then-else” statement: not at all*. You see, an “If-then-else” statement in your code creates a branch in the instruction list. If the statement is true, the processor will execute a particular instruction list, if not, it will execute another. The processor, always striving for optimizations, tries to predict which way the branch will go and pre-load the instructions. A wrong prediction is known as a “Branch Miprediction“. The penalty? In modern microprocessors, 10-20 cycles[1]. Your average 2.4GHz CPU can perform 2.400.000.000 cycles/second. That is 2.4 billion cycles per seconds, in case you haven’t noticed. Billions… Per second… So I think it’s pretty safe to say that this has absolutely no affect in your average pet-project.
One particular student, however, took this at face value and came up with the following gem:
public void doSomething(int code) { while ( code == 101 ) { doThis(); break; } while ( code == 102 ) { doThat(); break; } while ( code == 103 ) { justDoIt(); break; } ... } |
After I got over the initial shock I turned to him and asked “So why didn’t you use a for loop?” to which he replied “I would have, but the while loop came into my mind first.”
* Except if you are writing an extremely performance-critical application.

Hey, I’m pretty sure you meant an “If-Else” statement :)
Anyhow, this is pretty funny. Did you submit it to TDWTF?
May 5th, 2011 at 19:48Yes, you are correct. I am talking about an “If-Else” statement.
I did send this to TDWTF (ergo “CodeSOD”) but didn’t get a reply for over 3 months, so I decided to post in to my blog. I really wish they posted it. ;)
May 7th, 2011 at 10:36So basically, he reinvented the switch statement?
April 5th, 2012 at 11:27