Currently there are about acquiring milliseconds following three methods
//方法 一
System.currentTimeMillis();
//方法 二
Calendar.getInstance().getTimeInMillis();
//方法 三
new Date().getTime();
A recent monitoring system, the code has found the first two methods, and then suddenly had an idea, in the end Which is faster?
Then do the following experiment:
import java.util.Calendar;
import java.util.Date;
public class TimeTest {
private static long _TEN_THOUSAND=10000;
public static void main(String[] args) {
long times=1000*_TEN_THOUSAND;
long t1=System.currentTimeMillis();
testSystem(times);
long t2=System.currentTimeMillis();
System.out.println(t2-t1);
testCalander(times);
long t3=System.currentTimeMillis();
System.out.println(t3-t2);
testDate(times);
long t4=System.currentTimeMillis();
System.out.println(t4-t3);
}
public static void testSystem(long times){//use 188
for(int i=0;i<times;i++){
long currentTime=System.currentTimeMillis();
}
}
public static void testCalander(long times){//use 6299
for(int i=0;i<times;i++){
long currentTime=Calendar.getInstance().getTimeInMillis();
}
}
public static void testDate(long times){
for(int i=0;i<times;i++){
long currentTime=new Date().getTime();
}
}
}
I will not because it is simple to add a comment, and each method run 1 million times, and then view the run results
187
7032
297
It was found that System.currentTimeMillis () that the fastest way
Calendar.getInstance (). GetTimeInMillis () this way slowest to see the source code will find, Canlendar because to deal with time zones can take a lot of time.
It is proposed that more use of the first approach.
Another, System class there are many effective methods, for example, like arrayCopy