5 ms·
I think the reduction in the number of branches inside the loop is a significant factor here, i.e. the if statement is performed per 4,8 or 16 elements instead
by redcalx 8y ago
I think the reduction in the number of branches inside the loop is a significant factor here, i.e. the if statement is performed per 4,8 or 16 elements instead of per value element. Branches invoke branch prediction logic which is non trivial, thus even though it may not slow execution it may increase power consumption.
On this basis another way of approaching the problem is to loop over the whole array and return the result at the end, but this of course would take N/2 loops on average, whereas the nested if can exit early. A compromise might be to loop over short sub-spans of the array, and do an exit early test at the end of each sub-span.
A good sub-span length for scalar code might be around 16, for one because we hit the law of diminishing returns for longer spans.
Also I think is_sorted_asc() or is_sorted_ascending() might be a better name if this were for a function in a general purpose library.