Avatar ·

Why is conditional processing of a sorted array faster than an unsorted one?

Hi everyone! I'm a beginner in Java and encountered a very strange performance behavior. I have a simple code that sums array elements, but only if they are greater than a certain threshold. I noticed that if the array is pre-sorted, the code runs about 2-3 times faster! Here is my test code:
import java.util.Arrays;
import java.util.Random;

public class BranchPredictionTest {
    public static void main(String[] args) {
        int arraySize = 100000;
        int[] data = new int[arraySize];
        Random random = new Random(12345);
        
        // Fill the array with random values from 0 to 255
        for (int i = 0; i < arraySize; i++) {
            data[i] = random.nextInt(256);
        }
        
        // Create a co