Skip to content

Instantly share code, notes, and snippets.

@aschroder
Created March 14, 2012 08:13
Show Gist options
  • Save aschroder/2035049 to your computer and use it in GitHub Desktop.
Save aschroder/2035049 to your computer and use it in GitHub Desktop.
Test some Java loop optimization cf. http://pastebin.com/4edtQXmV
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