1.System.currentTimeMillis()
System类中的currentTimeMillis()方法是三种方式中效率最好的,运行时间最短。开发中如果设计到效率问题,推荐使用此种方式获取。
2.new Date().getTime()
除了System类,使用量很大的应该就是Date类了,但date类中获取时间戳并不是最有效率的,翻看他的源码:
无参构造如下
public Date() {
this(System.currentTimeMillis());
}
从源码可以看出,new Date()其实就是调用了System.currentTimeMillis(),再传入自己的有参构造函数。
不难看出,如果只是仅仅获取时间戳,即使是匿名的new Date()对象也会有些许的性能消耗,从提升性能的角度来看,只是仅仅获取时间戳,不考虑时区的影响,
直接调用System.currentTimeMillis()会更好一些。
3.Calendar.getInstance().getTimeInMillis()
这种方式其实是速度最慢,看其源码就会发现,Canlendar是区分时区的,因为要处理时区问题会耗费很多的时间。
package com.example.java_algorithms.javaBasic.time;
import java.util.Calendar;
import java.util.Date;
/**
* 三种时间戳获取方式效率比较
*/
public class TimeStampComparable {
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);
/**
testSystem:28
testCalander:1513
testDate:29
*/
}
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();
}
}
}