Why sorted arrays process 6x faster than unsorted arrays in conditional loops:
CPU branch predictors use historical pattern history tables to speculate which branch will be taken. Random unsorted data causes constant branch mispredictions, flushing the 14-20 stage CPU execution pipeline (costing 15-20 wasted clock cycles per branch!).
Branchless Clamp in C++:
// Branching (Misprediction risk)
int ClampBranch(int v, int minV, int maxV) {
if (v < minV) return minV;
if (v > maxV) return maxV;
return v;
}
// Branchless using CMOV (Conditional Move)
int ClampBranchless(int v, int minV, int maxV) {
v = (v < minV) ? minV : v;
v = (v > maxV) ? maxV : v;
return v; // Compiles directly to x86 'cmovl' and 'cmovg' instructions with 0 branches!
}