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

查看:30
本文介绍了System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,使用对性能和资源有何影响

In Java, what are the performance and resource implications of using

System.currentTimeMillis() 

对比

new Date() 

对比

Calendar.getInstance().getTime()

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

As I understand it, System.currentTimeMillis() is the most efficient. However, in most applications, that long value would need to be converted to a Date or some similar object to do anything meaningful to humans.

推荐答案

System.currentTimeMillis() 显然是最高效的,因为它甚至不创建对象,但是 new Date() 实际上只是一个很长的薄包装器,所以它也不甘落后.另一方面,Calendar 相对缓慢且非常复杂,因为它必须处理相当复杂的日期和时间(闰年、夏令时、时区、等).

System.currentTimeMillis() is obviously the most efficient since it does not even create an object, but new Date() is really just a thin wrapper about a long, so it is not far behind. Calendar, on the other hand, is relatively slow and very complex, since it has to deal with the considerably complexity and all the oddities that are inherent to dates and times (leap years, daylight savings, timezones, etc.).

在您的应用程序中只处理长时间戳或 Date 对象通常是一个好主意,并且仅在您实际需要执行日期/时间计算时才使用 Calendar,或格式化日期以向用户显示它们.如果你必须做很多这样的事情,使用 Joda Time 可能是一个好主意,对于清洁工来说界面和更好的性能.

It's generally a good idea to deal only with long timestamps or Date objects within your application, and only use Calendar when you actually need to perform date/time calculations, or to format dates for displaying them to the user. If you have to do a lot of this, using Joda Time is probably a good idea, for the cleaner interface and better performance.

这篇关于System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆