Calendar.getInstance()的性能問題

Calendar.getInstance()的性能問題

微信公眾號 51碼農網

專業編程問答社區

www.51manong.com

Calendar.getInstance()是非常耗時的操作。需要明確的是,日歷實際上不是單例。每次調用Calendar.getInstance()都會返回一個新對象。

查看源碼

public static Calendar getInstance()
    {
        Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
        cal.sharedZone = true;
        return cal;
    }

再看createCalendar方法

private static Calendar createCalendar(TimeZone zone,
                                           Locale aLocale)
    {
        Calendar cal = null;

        String caltype = aLocale.getUnicodeLocaleType("ca");
        if (caltype == null) {
            // Calendar type is not specified.
            // If the specified locale is a Thai locale,
            // returns a BuddhistCalendar instance.
            if ("th".equals(aLocale.getLanguage())
                    && ("TH".equals(aLocale.getCountry()))) {
                cal = new BuddhistCalendar(zone, aLocale);
            } else {
                cal = new GregorianCalendar(zone, aLocale);
            }
        } else if (caltype.equals("japanese")) {
            cal = new JapaneseImperialCalendar(zone, aLocale);
        } else if (caltype.equals("buddhist")) {
            cal = new BuddhistCalendar(zone, aLocale);
        } else {
            // Unsupported calendar type.
            // Use Gregorian calendar as a fallback.
            cal = new GregorianCalendar(zone, aLocale);
        }

        return cal;
    }

代碼中可以清楚的看到是每次都創建的。

看看使用System.currentTimeMillis()和Calendar.getInstance()的性能差別

public class Test1 {
   public static void main(String[] args) {
       int runs = 10000;  
       long start = System.nanoTime();  
       Calendar cal = null;  
       for(int i=0;i<runs;i++)  
           cal = Calendar.getInstance();  
       long time = System.nanoTime() - start;  
       System.out.println("Calendar.getInstance() took on average "+time/runs+" ns. "+cal);  

       long start2 = System.nanoTime();  
       long now = 0;  
       for(int i=0;i<runs;i++)  
           now = System.currentTimeMillis();  
       long time2 = System.nanoTime() - start2;  
       System.out.println("System.currentTimeMillis() took on average "+time2/runs+" ns. "+now);  

}

結果:

Calendar.getInstance() took on average 29348 ns. java.util.GregorianCalendar[time=1569646753165,.......]
System.currentTimeMillis() took on average 89 ns. 1569646753167

微信公眾號:51碼農網

Calendar.getInstance()的性能問題

原文 

https://segmentfault.com/a/1190000020605368

本站部分文章源于互聯網,本著傳播知識、有益學習和研究的目的進行的轉載,為網友免費提供。如有著作權人或出版方提出異議,本站將立即刪除。如果您對文章轉載有任何疑問請告之我們,以便我們及時糾正。

PS:推薦一個微信公眾號: askHarries 或者qq群:474807195,里面會分享一些資深架構師錄制的視頻錄像:有Spring,MyBatis,Netty源碼分析,高并發、高性能、分布式、微服務架構的原理,JVM性能優化這些成為架構師必備的知識體系。還能領取免費的學習資源,目前受益良多

轉載請注明原文出處:Harries Blog? » Calendar.getInstance()的性能問題

贊 (0)
分享到:更多 ()

評論 0

  • 昵稱 (必填)
  • 郵箱 (必填)
  • 網址
手机彩票计划软件超稳