do-while文の等価な制御構造の速さをJavaで測定してみた。

 do-while文の等価な制御構造の速さをJavaで測定してみました。(^_^;
 ブログラムと結果は次の通り。やっぱり、ふつうに、while(true)やfor(;;)の方が速いですね。ちなみに、なぜか、whileとforの順番は位置によって微妙に変わります。たとえば、for1文の方をwhile文の前にもってきて測定するとwhile文の方が速くなったりします。(^_^;

●DoWhileTest1.java

/* 
 * DoWhileTest1.java
 */

class DoWhileTest1 {
    public static void main(String[] args) {
        final int N=Integer.MAX_VALUE;
        long tm;
        int x;
        
        //System.out.println(N);

        //--- do-while文 ---//
        tm=System.nanoTime();       // Timer Start
        x=0;
        do {
            x+=1;
        } while(x< N);
        tm=System.nanoTime()-tm;        // Timer Stop
        System.out.printf("do-while文 : %.3f [sec]\n",(double)tm/1e9);
        
        //--- while文 ---//
        tm=System.nanoTime();       // Timer Start
        x=0;
        while(true) {
            x+=1;
            if(!(x< N)) break;
        }
        tm=System.nanoTime()-tm;        // Timer Stop
        System.out.printf("while文    : %.3f [sec]\n",(double)tm/1e9);
        
        //--- for文1 ---//
        tm=System.nanoTime();       // Timer Start
        x=0;
        for(;;) {
            x+=1;
            if(!(x< N)) break;
        }
        tm=System.nanoTime()-tm;        // Timer Stop
        System.out.printf("for文1     : %.3f [sec]\n",(double)tm/1e9);
        
        //--- for文2 ---//
        tm=System.nanoTime();       // Timer Start
        x=0;    // lcc: loop-continuation-condition
        for(boolean lcc=true; lcc; lcc=(x< N)? true: false){
            x+=1;
        }
        tm=System.nanoTime()-tm;        // Timer Stop
        System.out.printf("for文2     : %.3f [sec]\n",(double)tm/1e9);
    }
}

●実行結果

do-while文 : 1.342 [sec]
while文    : 1.334 [sec]
for文1     : 1.327 [sec]
for文2     : 2.296 [sec]

明解Java 入門編

明解Java 入門編

スッキリわかるJava入門

スッキリわかるJava入門

わかりやすいJava入門編

わかりやすいJava入門編