Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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