0

I wrote a method and when I added some insignificant code like this:

array[1]=array[1];
array[0]=array[0];
array[3]=array[3];
array[2]=array[2];

it worked faster!

I used double t = System.currentTimeMillis(); at first to record the time.
Then I called the method and used System.out.println(System.currentTimeMillis()-t); at the end.

Without the code (array[1]=array[1];...) the runing time was 1035.0 ms, but if with the code added, the running time became 898.0ms.

Here is my method and my code. PS:this method is used for the game 2048, exp: {2,2,2,2} trans to {0,0,4,4}

static void toRight2(int[] array){
    if (array[2]==array[3]  ) {
        array[3]=array[2]*2;
        if (array[0]==array[1]) {
            array[2]=array[1]*2;
            array[0]=0;
            array[1]=0;
        }else {
            array[2]=array[1];
            array[1]=array[0];
            array[0]=0;
        }
    } else{
        if (array[0]==array[1]) {
            array[1]=array[1]*2;
            array[0]=0;
            array[3]=array[3];
            array[2]=array[2];
        }else {
            array[1]=array[1];//delete this cost more time
            array[0]=array[0];//delete this cost more time 
            array[3]=array[3];//delete this cost more time
            array[2]=array[2];//delete this cost more time
        } 
    }

}

public static void main(String[] args) {
    double t=System.currentTimeMillis();
    int[] array={1,2,3,3};
    for (int j = 2; j <400*1000000; j++) {
         toRight2(array);
    }
    System.out.println(System.currentTimeMillis()-t);
}
savanto
  • 4,470
  • 23
  • 40
Zizy
  • 191
  • 1
  • 1
  • 7
  • 1
    http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Lorenzo Boccaccia Jun 06 '14 at 09:25
  • 2
    Please read http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – NPE Jun 06 '14 at 09:25
  • thx for your answers, when i add warmup phase before recoding time it's works well ,like : for (int i = 0; i < 100000000l; i++); but why =A=, i can not find any relation between warmup phase and my insignificant code, is this because i add more insignificant code let the JVM warm up? – Zizy Jun 06 '14 at 09:44

0 Answers0