Avatar ·

Why processing a sorted array is faster than an unsorted one

Hello, colleagues! I'm a beginner Java developer and encountered strange behavior in my code. I have a simple performance test: I sum all array elements that are greater than a certain threshold. But I noticed that if the array is pre-sorted, the code runs 2-3 times faster! Here's my code: ```java public class BranchPredictionTest { public static void main(String[] args) { int size = 100000; int[] data = new int[size]; Random rand = new Random(); for (int i = 0; i < size; i++) { data[i] = rand.nextInt(256); } // Sort the array int[] sorted = data.clone(); Arrays.sort(sorted); long start = System.nanoTime(); long sumSorted = processArray(sorted