Created
March 14, 2012 08:13
-
-
Save aschroder/2035049 to your computer and use it in GitHub Desktop.
Test some Java loop optimization cf. http://pastebin.com/4edtQXmV
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 TestOptimizations { | |
private static final String str = "abcdefg"; | |
private static long nothing = 0; | |
public static void main(String[] args) { | |
// try swapping the order of these first two calls. | |
System.out.println("inline (ms): " + runLoopInline(10000000)); | |
System.out.println("precalc (ms): " + runLoopPrecalc(10000000)); | |
System.out.println("precalc (ms): " + runLoopPrecalc(20000000)); | |
System.out.println("inline (ms): " + runLoopInline(20000000)); | |
System.out.println("precalc (ms): " + runLoopPrecalc(30000000)); | |
System.out.println("inline (ms): " + runLoopInline(30000000)); | |
} | |
private static long runLoopInline(int numTests) { | |
long blah = 0; | |
long start = System.currentTimeMillis(); | |
for (int j = 0; j < numTests; j++) { | |
for (int i = 0; i < str.length(); i++) { | |
blah = 2*i*j; | |
} | |
} | |
nothing = blah; // try commenting this out... | |
return System.currentTimeMillis() - start; | |
} | |
private static long runLoopPrecalc(int numTests) { | |
long blah = 0; | |
int length = str.length(); | |
long start = System.currentTimeMillis(); | |
for (int j = 0; j < numTests; j++) { | |
for (int i = 0; i < length; i++) { | |
blah = 2*i*j; | |
} | |
} | |
nothing = blah; // try commenting this out... | |
return System.currentTimeMillis() - start; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment