Created
February 20, 2012 20:36
-
-
Save shemnon/1871252 to your computer and use it in GitHub Desktop.
Permission (guard blocks) vs. Forgiveness (catching NPEs)
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
import java.util.Arrays; | |
import java.util.Random; | |
import java.util.concurrent.Callable; | |
public class PermissionVsForgiveness { | |
int[] a1, a2, a3, a4; | |
Callable<Integer> permission = new Callable<Integer>() { | |
public Integer call() throws Exception { | |
if (a1 == null || a2 == null || a3 == null || a4 == null) return 0; | |
return a1[0] + a2[0] + a3[0] + a4[0]; | |
} | |
}; | |
Callable<Integer> forgiveness = new Callable<Integer>() { | |
public Integer call() throws Exception { | |
try { | |
return a1[0] + a2[0] + a3[0] + a4[0]; | |
} catch (NullPointerException npe) { | |
return 0; | |
} | |
} | |
}; | |
Callable<Integer> ignorance = new Callable<Integer>() { | |
public Integer call() throws Exception { | |
return 0; | |
} | |
}; | |
public static void main(String args[]) { | |
try { | |
new PermissionVsForgiveness().calculate(100); | |
System.out.println(); | |
new PermissionVsForgiveness().calculate(10000); | |
System.out.println(); | |
new PermissionVsForgiveness().calculate(1000000); | |
} catch (Exception e) { | |
System.out.println("oopsies!"); | |
e.printStackTrace(); | |
} | |
} | |
public void calculate(int iterations) throws Exception { | |
Random rand = new Random(); | |
for (Callable<Integer> notALambda : Arrays.asList(permission, forgiveness, ignorance)) { | |
for (int fraction = 1; fraction < 20; fraction++) { | |
double frequency = 1.0 / (1 << fraction); | |
int foolHotspot = 0; | |
long start = System.currentTimeMillis(); | |
for (int i = 0; i < iterations; i++) { | |
a1 = new int[]{i}; | |
a2 = new int[]{i}; | |
a3 = new int[]{i}; | |
a4 = new int[]{i}; | |
if (rand.nextDouble() < frequency) { | |
a1 = null; | |
a2 = null; | |
a3 = null; | |
a4 = null; | |
} | |
foolHotspot += notALambda.call(); | |
} | |
long end = System.currentTimeMillis(); | |
System.gc(); | |
System.gc(); | |
System.gc(); | |
if (foolHotspot * start == end) System.out.println("Whodathough"); | |
System.out.println( | |
String.format("%f%% %fms", | |
frequency * 100, ((end - start) / ((double) iterations)) * 1000)); | |
} | |
System.out.println(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment