CodeSOD: How to avoid the expensive “If-then-else” statement

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 ) {
  while ( code == 102 ) {
  while ( code == 103 ) {

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.


[1]: Branch Predictor - Wikipedia

CodePanagiotis PeikidisCode, fun, java