Created
December 11, 2022 16:15
-
-
Save shai-almog/5b5a0a16feadf8d5f702f236d191d9fe to your computer and use it in GitHub Desktop.
One loop outperforms two
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
private static final int SIZE = 5_000_000; | |
private static final int[] arr1 = initArray(SIZE); | |
private static final int[] arr2 = initArray(SIZE); | |
public static void main(String[] args) throws InterruptedException { | |
// warmup | |
long[] results = new long[6]; | |
results[0] = twoLoops(); | |
results[1] = oneLoop(); | |
results[2] = twoLoops(); | |
results[3] = oneLoop(); | |
// give the jit time to recover | |
Thread.sleep(1000); | |
long time1 = System.currentTimeMillis(); | |
results[4] = oneLoop(); | |
long endTime1 = System.currentTimeMillis(); | |
long time2 = System.currentTimeMillis(); | |
results[5] = twoLoops(); | |
long endTime2 = System.currentTimeMillis(); | |
System.out.println("Junk against optimization out: " + Arrays.toString(results)); | |
System.out.println("One Loop: " + (endTime1 - time1)); | |
System.out.println("Two Loops: " + (endTime2 - time2)); | |
} | |
private static int[] initArray(int size) { | |
Random random = new Random(); | |
int[] primitives = new int[size]; | |
for (int iter = 0 ; iter < primitives.length ; iter++) { | |
primitives[iter] = random.nextInt(); | |
} | |
return primitives; | |
} | |
private static long twoLoops() { | |
long sum1 = 0; | |
long sum2 = 0; | |
for(int iter = 0 ; iter < arr1.length ; iter++) { | |
sum1 += arr1[iter]; | |
} | |
for(int iter = 0 ; iter < arr2.length ; iter++) { | |
sum2 += arr2[iter]; | |
} | |
return Math.max(sum1, sum2); | |
} | |
private static long oneLoop() { | |
long sum1 = 0; | |
long sum2 = 0; | |
for(int iter = 0 ; iter < arr1.length ; iter++) { | |
sum1 += arr1[iter]; | |
sum2 += arr2[iter]; | |
} | |
return Math.max(sum1, sum2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment