In C++, is it better to cap a value using std::min or an if branch?
c++, cpu, instruction-set, minimum
Solution
Modern compilers are smart enough to generate the same code in both cases. For example, 32-bit GCC generates:
addl %esi, %edi
cmpl %edx, %edi
movl %edi, %eax
cmovgl %edx, %eax
64-bit Clang:
%1 = add nsw i32 %increment, %value
%2 = icmp sgt i32 %1, %valueMax
%value = select i1 %2, i32 %valueMax, i32 %1
Problem
A very common pattern in programming is to cap a value at a maximum after some kind of update. What I'd like to know, is if there's a difference between the following two pieces of code, and if one should be preferred: ``` value += increment; value = std::min(value, valueMax); ``` vs ``` value += increment; if (value > valueMax) value = valueMax; ``` My thinking is that this comes down to whether CPUs have instructions for taking two values and producing the minumum. If so, the call to std::min should result in this instruction and avoid an unnecessary branch. If not, the second version avoids an unnecessary assignment when value <= valueMax. I'm not very good with this kind of thing, but I'm sure there's old-school assembly hackers who would know this. To them I ask: which is better?