在 Java 中,使用的性能和资源影响是什么
System.currentTimeMillis()
对比
new Date()
对比
Calendar.getInstance().getTime()
据我了解,System.currentTimeMillis()
是最有效的。但是,在大多数应用程序中,需要将 long 值转换为 Date 或一些类似的对象才能对人类做任何有意义的事情。
在 Java 中,使用的性能和资源影响是什么
System.currentTimeMillis()
对比
new Date()
对比
Calendar.getInstance().getTime()
据我了解,System.currentTimeMillis()
是最有效的。但是,在大多数应用程序中,需要将 long 值转换为 Date 或一些类似的对象才能对人类做任何有意义的事情。
System.currentTimeMillis()
显然是最有效的,因为它甚至不创建对象,但new Date()
实际上只是一个很长的薄包装器,所以它也不甘落后。Calendar
另一方面,它相对缓慢且非常复杂,因为它必须处理日期和时间(闰年、夏令时、时区等)所固有的相当复杂和所有奇怪的问题。
通常最好只处理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());
}
因此,除非您想在使用它创建日历/日期对象之前对其进行一些数学运算,否则实际上不需要专门获取系统时间。如果您的目的是大量使用日期计算,我还必须推荐joda-time来替代 Java 自己的日历/日期类。
如果您使用日期,那么我强烈建议您使用 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 次) = 402ms 新日期().getTime(); (*1000000 次) = 18ms System.currentTimeMillis() (*1000000 次) = 16ms
不要忘记 GC(如果你使用Calendar.getInstance()
or new Date()
)
我更喜欢将返回的值System.currentTimeMillis()
用于所有类型的计算,并且仅在Calendar
或者Date
我需要真正显示人类读取的值时才使用。这也将防止 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
当前时间米利斯():3
System.currentTimeMillis()
显然是最快的,因为它只是一个方法调用,不需要垃圾收集器。