Java中獲取時(shí)間戳的三種方式對(duì)比實(shí)現(xiàn)
Java中獲取時(shí)間戳 三種方式對(duì)比
最近項(xiàng)目開發(fā)過(guò)程中發(fā)現(xiàn)了項(xiàng)目中獲取時(shí)間戳的業(yè)務(wù)。而獲取時(shí)間戳有以下三種方式,首先先聲明推薦使用System類來(lái)獲取時(shí)間戳,下面一起看一看三種方式。
1.System.currentTimeMillis()System類中的currentTimeMillis()方法是三種方式中效率最好的,運(yùn)行時(shí)間最短。開發(fā)中如果設(shè)計(jì)到效率問(wèn)題,推薦使用此種方式獲取。
System.currentTimeMillis()2.new Date().getTime()
除了System類,使用量很大的應(yīng)該就是Date類了,包括我也一樣開發(fā)中如果涉及到日期的首先會(huì)想到Date,但date類中獲取時(shí)間戳并不是最有效率的,翻看他的源碼:無(wú)參構(gòu)造如下👇
public Date() { this(System.currentTimeMillis());}
從源碼可以看出,new Date()其實(shí)就是調(diào)用了System.currentTimeMillis(),再傳入自己的有參構(gòu)造函數(shù)。不難看出,如果只是僅僅獲取時(shí)間戳,即使是匿名的new Date()對(duì)象也會(huì)有些許的性能消耗, 從提升性能的角度來(lái)看,只是僅僅獲取時(shí)間戳,不考慮時(shí)區(qū)的影響(時(shí)區(qū)為什么會(huì)有影響看下一段),直接調(diào)用System.currentTimeMillis()會(huì)更好一些。
3.Calendar.getInstance().getTimeInMillis()這種方式其實(shí)是速度最慢,看其源碼就會(huì)發(fā)現(xiàn),Canlendar是區(qū)分時(shí)區(qū)的,因?yàn)橐幚頃r(shí)區(qū)問(wèn)題會(huì)耗費(fèi)很多的時(shí)間。
附測(cè)試如下:
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
Calendar.getInstance().getTimeInMillis() 這種方式速度最慢,這是因?yàn)镃anlendar要處理時(shí)區(qū)問(wèn)題會(huì)耗費(fèi)較多的時(shí)間。
到此這篇關(guān)于Java中獲取時(shí)間戳的三種方式對(duì)比實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Java 獲取時(shí)間戳內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. css進(jìn)階學(xué)習(xí) 選擇符2. python實(shí)現(xiàn)自動(dòng)化辦公郵件合并功能3. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))4. python爬蟲beautifulsoup解析html方法5. python web框架的總結(jié)6. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式7. 解決python logging遇到的坑 日志重復(fù)打印問(wèn)題8. html小技巧之td,div標(biāo)簽里內(nèi)容不換行9. Python基礎(chǔ)之numpy庫(kù)的使用10. 詳解Python模塊化編程與裝飾器
