21 ms·
His answer does include what I would think is the correct reason in that specific case though - branch prediction on the if(data[c] >= 128) line. When the a
by robmccoll 7y ago
His answer does include what I would think is the correct reason in that specific case though - branch prediction on the
if(data[c] >= 128)
line. When the array is sorted, you would go from not taken to taken only once and likely get correct predictions nearly 100% of the time versus the shuffled list producing a rate around 50% depending on the predictor.
Also check out the first response for a nice explanation and an optimization to eliminate the branch. The author replaced it with a bit twiddling solution to either store the current element or zero if it is less than 128 in a temporary variable and then always add that to the sum.