Java System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/368094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:53:34  来源:igfitidea点击:

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

javaperformancedatetimecalendar

提问by Vihung

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

在 Java 中,使用的性能和资源影响是什么?

System.currentTimeMillis() 

vs.

对比

new Date() 

vs.

对比

Calendar.getInstance().getTime()

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()是最有效的。但是,在大多数应用程序中,需要将该长值转换为 Date 或一些类似的对象才能执行对人类有意义的任何操作。

采纳答案by Michael Borgwardt

System.currentTimeMillis()is obviously the most efficientsince 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.).

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

It's generally a good idea to deal only with long timestamps or Dateobjects within your application, and only use Calendarwhen 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 Timeis probably a good idea, for the cleaner interface and better performance.

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

回答by Bombe

I prefer using the value returned by System.currentTimeMillis()for all kinds of calculations and only use Calendaror Dateif I need to really display a value that is read by humans. This will also prevent 99% of your daylight-saving-time bugs. :)

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

回答by krosenvold

If you're USING a date then I strongly advise that you use jodatime, http://joda-time.sourceforge.net/. Using System.currentTimeMillis()for fields that aredates sounds like a very bad idea because you'll end up with a lot of useless code.

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

Both date and calendar are seriously borked, and Calendar is definitely the worst performer of them all.

日期和日历都严重乏味,日历绝对是其中表现最差的。

I'd advise you to use System.currentTimeMillis()when you are actually operating with milliseconds, for instance like this

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

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

回答by Esko

Looking at the JDK, innermost constructor for Calendar.getInstance()has this:

查看 JDK,最里面的构造函数Calendar.getInstance()有:

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

so it already automatically does what you suggest. Date's default constructor holds this:

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

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

So there really isn't need to get system time specifically unless you want to do some math with it before creating your Calendar/Date object with it. Also I do have to recommend joda-timeto use as replacement for Java's own calendar/date classes if your purpose is to work with date calculations a lot.

所以真的不需要专门获取系统时间,除非你想在用它创建日历/日期对象之前用它做一些数学运算。如果您的目的是大量处理日期计算,我也必须推荐joda-time来替代 Java 自己的日历/日期类。

回答by MykennaC

Depending on your application, you may want to consider using System.nanoTime()instead.

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

回答by Puzirki

On my machine I tried check it. My result:

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

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

Don't forget about GC (if you use Calendar.getInstance()or new Date())

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

回答by wiji

I tried this:

我试过这个:

        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);

And result was:

结果是:

Date(): 199

日期():199

currentTimeMillis(): 3

currentTimeMillis(): 3

回答by Ramón

System.currentTimeMillis()is obviously the fastest because it's only one method call and no garbage collector is required.

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