Improvement to three-way min

I was working with Wagner-Fischer this time. The plan didn't work out too well, because the algorithm was still way to slow for my needs, but I did try to optimise what can be optimised and Visual Studio performance analyser showed that std::min, the std::initializer_list version, was taking a lot of time. Since I only need the smallest number not in a general case, but for a specific case of three numbers for Wagner-Fischer, I was thinking I can get better performance out of this. It was one of those rare cases where micro optimisation matters. Since the correct code was relatively hard to find online, contrary to my expectations for a task this simple, I offer it here for future generations to copy/paste, along with the string I was searching for originaly: find smallest of 3 numbers c++.


// Beware, min-field ahead!
min = min1 < min2 ?
      (min1 < min3 ? min1 : min3) :
      (min2 < min3 ? min2 : min3);

Measurements have shown it is about 2x-3x faster than using std::min({1,2,3}) with Visual Studio compiler (2013 version) and 7x with gcc v4.8, and about 50% faster than using std::min(1,std::min(2,3)) with VS compiler and 30% with GCC. No wonder; it takes at most two comparissons.

On second thought, this is not just sometimes useful. If wrapped into an efficient function, there are measurable gains and no obvious downsides.


Previous: Strict type-safety framework
Next: When to use Barnes-Hut simulation