在Java中,使用的性能和资源含义是什么

System.currentTimeMillis() 

vs.

new Date() 

vs.

Calendar.getInstance().getTime()

根据我的理解,System.currentTimeMillis()是最有效的。但是,在大多数应用程序中,需要将该长值转换为Date或一些类似的对象,才能执行对人类有意义的操作。


当前回答

根据应用程序的不同,您可能会考虑使用System.nanoTime()。

其他回答

我更喜欢使用System.currentTimeMillis()返回的值进行各种计算,如果我需要真正显示由人类读取的值,则只使用Calendar或Date。这也可以防止99%的夏令时错误。:)

如果你正在使用一个日期,那么我强烈建议你使用jodatime, http://joda-time.sourceforge.net/。对于日期字段使用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())

查看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自己的日历/日期类。

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