clang compiles all three of these functions to use max instructions (
https://godbolt.org/z/9z7hGfdhq).
#include <algorithm>
using std::max;
int max_array_func(int values[], size_t values_count)
{
int max_value = values[0];
for (size_t j = 0; j < values_count; j++)
{
max_value = max(max_value, values[j]);
}
return max_value;
}
int max_array_bittwiddling(int values[], size_t values_count)
{
int max_value = values[0];
for (size_t j = 0; j < values_count; j++)
{
int x = max_value;
int y = values[j];
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
max_value = x ^ ((x ^ y) & -(x < y));
}
return max_value;
}
int max_array_branch(int values[], size_t values_count)
{
int max_value = values[0];
for (size_t j = 0; j < values_count; j++)
{
if (max_value > values[j])
{
max_value = values[j];
}
}
return max_value;
}