continueを使うと遅くなるか?
Eclipse JUNOを入れがてら。
これと
// ifとelseで「対極的な処理をやってます」が見える書き方 for (int ii = 0; ii < LOOP; ii++) { if (ii % 2 == 0) { val++; } else { val--; } }
これは
// 無駄なインデントは悪! else以降がおっきくなってきたらelseのブロックが // ながーくなるのでこっちの方がイイゼ!の書き方 for (int ii = 0; ii < LOOP; ii++) { if (ii % 2 == 0) { val++; continue; } val--; }
速度に影響があるか検証。
検証コード
package test; public class TestMain { private static final int LOOP = 100_000_000; public static void main(String[] args) { TestMain testMain = new TestMain(); for (int ii = 0; ii < 10; ii++) { testMain.exec(); } } public void exec() { long t1, time; // continueなし t1 = System.nanoTime(); noContinue(); time = System.nanoTime() - t1; System.out.println(String.format("noContinue\t%d", time)); // continueあり t1 = System.nanoTime(); useContinue(); time = System.nanoTime() - t1; System.out.println(String.format("useContinue\t%d", time)); } private void noContinue() { int val = 0; for (int ii = 0; ii < LOOP; ii++) { if (ii % 2 == 0) { val++; } else { val--; } } } private void useContinue() { int val = 0; for (int ii = 0; ii < LOOP; ii++) { if (ii % 2 == 0) { val++; continue; } val--; } } }
結果
noContinue 4294387 useContinue 1332306 noContinue 45845 useContinue 571489 noContinue 350 useContinue 0 noContinue 700 useContinue 350 noContinue 350 useContinue 1050 noContinue 0 useContinue 0 noContinue 0 useContinue 0 noContinue 350 useContinue 350 noContinue 349 useContinue 0 noContinue 0 useContinue 0
最初の1、2回目はウォームアップとして、1億回実行してこの差。
まぁ、変わらんという事ですかね。