why i add more insignificant code but cost less time
- by user3714382
i write a method and when i add some insignificant code it works faster,
like these :
array[1]=array[1];
array[0]=array[0];
array[3]=array[3];
array[2]=array[2];
i use double t=System.currentTimeMillis(); at first to record the time.
then call the method
and use System.out.println(System.currentTimeMillis()-t); in the end.
when i delete the code (array[1]=array[1];...) the cost time is 1035.0 ms,but if i add these code,
the cost time become 898.0ms.
here is my method and my code. PS:this method is use 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);
}