繁体   English   中英

System.currentTimeMillis()与新Date()与Calendar.getInstance()。getTime()

[英]System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

在Java中,使用会对性能和资源产生什么影响

System.currentTimeMillis() 

new Date() 

Calendar.getInstance().getTime()

据我了解, System.currentTimeMillis()是最有效的。 但是,在大多数应用程序中,该长值需要转换为Date或某个类似的对象才能对人类有意义。

System.currentTimeMillis()显然是最高效的,因为它甚至都没有创建对象,但是new Date()实际上只是很薄的包装,大约很长一段时间,因此它并不落后。 另一方面, Calendar相对较慢且非常复杂,因为它必须处理日期和时间(le年,夏时制,时区等)所固有的相当大的复杂性和所有奇数。

通常,最好只处理应用程序中的长时间戳或Date对象,并且仅在实际需要执行日期/时间计算或格式化日期以将其显示给用户时才使用Calendar 如果您需要做很多事情,那么使用Joda Time可能是一个好主意,因为它具有更干净的界面和更好的性能。

看一下JDK, Calendar.getInstance()最里面的构造函数是这样的:

public GregorianCalendar(TimeZone zone, Locale aLocale) {
    super(zone, aLocale);
    gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
    setTimeInMillis(System.currentTimeMillis());
}

因此它已经可以自动执行您的建议。 Date的默认构造函数包含以下内容:

public Date() {
    this(System.currentTimeMillis());
}

因此,实际上确实不需要专门获取系统时间,除非您想使用它来做一些数学运算,然后再使用它创建Calendar / Date对象。 另外,如果您的目的是大量处理日期计算,那么我确实必须建议使用joda-time来代替Java自己的日历/日期类。

如果您要使用日期,则强烈建议您使用http://joda-time.sourceforge.net/的 jodatime。 使用System.currentTimeMillis()对于那些像一个非常糟糕的主意日期声音场,因为你有很多无用的代码而告终。

日期和日历都严重地令人厌烦,日历绝对是其中表现最差的。

我建议您在实际以毫秒为单位进行操作时使用System.currentTimeMillis() ,例如这样

 long start = System.currentTimeMillis();
    .... do something ...
 long elapsed = System.currentTimeMillis() -start;

在我的机器上,我尝试检查它。 我的结果:

Calendar.getInstance().getTime() (*1000000 times) = 402ms
new Date().getTime(); (*1000000 times) = 18ms
System.currentTimeMillis() (*1000000 times) = 16ms

不要忘了GC(如果使用Calendar.getInstance()new Date()

我更喜欢将System.currentTimeMillis()返回的值用于所有类型的计算,并且仅在我需要真正显示人类可以读取的值时才使用CalendarDate 这还将防止您的夏时制错误的99%。 :)

根据您的应用程序,您可能需要考虑使用System.nanoTime()

我尝试了这个:

        long now = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            new Date().getTime();
        }
        long result = System.currentTimeMillis() - now;

        System.out.println("Date(): " + result);

        now = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            System.currentTimeMillis();
        }
        result = System.currentTimeMillis() - now;

        System.out.println("currentTimeMillis(): " + result);

结果是:

日期():199

currentTimeMillis():3

System.currentTimeMillis()显然是最快的,因为它只是一个方法调用,不需要垃圾收集器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM