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
No answers yet.
Log in to leave an answer
Blogs
Design Patterns in C++ with Examples: A Complete Guide
API Gateway for Microservices in JavaScript: Complete Guide
Mutation Testing in TypeScript: Breaking Code to Make It Better
How to Change Background Color in SwiftUI: Best Practices 2025