Cratylus
Cratylus

Reputation: 54074

Is there a difference between the `if else` and the `if-else if-else`?

In WikiPedia article for Binary Search there is a section called Deferred detection of equality which presents a somewhat "optimized" version of binary search as follows:

int binary_search(int A[], int key, int imin, int imax)  
{  
  while (imax > imin)  
  {  
    int imid = (imin + imax) / 2;  
    if (A[imid] < key)  
      imin = imid + 1;  
    else  
      imax = imid;  
  }  
  if((imax == imin) && (A[imin] == key))  
    return imin;  
  else  
    return KEY_NOT_FOUND;  
}  

It is claimed that this is a better version than the conventional textbook binary search since the .... algorithm uses only one conditional branch per iteration
Is this true? I mean the if instructions are translated in CMP and Branch instructions in assembly so I can not think how an if-else is better than an if-else if-else
Is there such a difference that I should take into account in higher level languages? The code of the "deffered" version seems more tight I admin, but are there optimizations or penalties in how you form if-else statements?

Upvotes: 2

Views: 362

Answers (1)

Jon
Jon

Reputation: 437386

The key concept is that it uses one less conditional per iteration. That is, the equality check has been moved outside the while loop so that it only runs once, while in the basic version it would need to be checked every time¹.

That said, I 'm not sure if there would actually be a measurable difference when using the optimized form. For example, consider that:

  1. If all you are comparing is two integers then the compiler can detect that it can compute the comparison result just once and then evaluate which branch to take just as well.
  2. Binary search is O(logN), so the number of iterations taken would actually be very small even if the number of elements to search is quite large. It's arguable whether you 'd see any difference.
  3. The implementation of modern CPUs features such as speculative execution and branch prediction (especially in "nice" algorithms like binary search) might very well have more visible effects than this optimization (out of my league to check though).

Notes:

¹ Actually it is another condition that doesn't need to be checked when the equality comparison moves out, but conceptually there is no difference.

Upvotes: 3

Related Questions