**
Java中獲取時間戳 三種方式對比
**
最近專案開發程序中發現了專案中獲取時間戳的業務,而獲取時間戳有以下三種方式,首先先宣告推薦使用System類來獲取時間戳,下面一起看一看三種方式,
1.System.currentTimeMillis()
System類中的currentTimeMillis()方法是三種方式中效率最好的,運行時間最短,開發中如果設計到效率問題,推薦使用此種方式獲取,
System.currentTimeMillis()
2.new Date().getTime()
除了System類,使用量很大的應該就是Date類了,包括我也一樣開發中如果涉及到日期的首先會想到Date,但date類中獲取時間戳并不是最有效率的,翻看他的原始碼:
無參構造如下👇
public Date() {
this(System.currentTimeMillis());
}
從原始碼可以看出,new Date()其實就是呼叫了System.currentTimeMillis(),再傳入自己的有參建構式,不難看出,如果只是僅僅獲取時間戳,即使是匿名的new Date()物件也會有些許的性能消耗, 從提升性能的角度來看,只是僅僅獲取時間戳,不考慮時區的影響(時區為什么會有影響看下一段),直接呼叫System.currentTimeMillis()會更好一些,
3.Calendar.getInstance().getTimeInMillis()
這種方式其實是速度最慢,看其原始碼就會發現,Canlendar是區分時區的,因為要處理時區問題會耗費很多的時間,
附測驗如下:
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();
}
}
}
效果如下
187
7032
297
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/250212.html
標籤:java
