简体   繁体   English

System.currentTimeMillis()和Date getTime()之间的区别?

[英]Difference between System.currentTimeMillis() and Date getTime()?

I was hoping to squeeze a tiny performance gain out of many calls to a function that returns a timestamp. 我希望通过对返回时间戳的函数的多次调用来获得微小的性能提升。 The function looks like this: 该函数如下所示:

public static long get_now_ms(){
    // returns number of MILLISECONDS since epoch
    java.util.Date d = new java.util.Date();
    return d.getTime();
}

Can I just replace this with: 我可以用以下内容替换它:

public static long get_now_ms(){
    // returns number of MILLISECONDS since epoch
    return System.currentTimeMillis();
}

I know that Date internally uses System.currentTimeMillis(). 我知道Date内部使用System.currentTimeMillis()。 My question is more whether or not daylight savings time or time zone could ever lead to a difference in result with these two approaches. 我的问题是,夏令时或时区是否会导致这两种方法的结果出现差异。 I imagine this may come up with Calendar objects, but not Date objects, but would love some clarification on this. 我想这可能会出现Calendar对象,但不是Date对象,但是会对此有所了解。

I know I will likely not see an appreciable difference in performance in a real-world application, but would nevertheless like to know the answer. 我知道我可能不会在实际应用程序中看到明显的性能差异,但仍然想知道答案。

Thanks! 谢谢!

No difference, except for the very slight lag caused by allocating a Date object. 没有区别,除了分配Date对象造成的非常轻微的延迟。

From the javadoc the the default constructor of Date : javadoc开始Date的默认构造函数:

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. 分配一个Date对象并对其进行初始化,使其表示分配时间,测量精确到毫秒。

A Date is just a thin wrapper around the epoch milliseconds, without any concept of timezones. Date只是一个Date毫秒的薄包装器,没有任何时区概念。 Only when rendered to a String is timezone considered, but that is handled by the Locale class. 只有在渲染到String时才会考虑时区,但这是由Locale类处理的。

I would suggest running a unit test (ex. https://gist.github.com/ledlogic/8532028 ). 我建议进行单元测试(例如https://gist.github.com/ledlogic/8532028 )。 I saw only a slight overall benefit to running the System.currentTimeMillis versus the (new Date()).getTime(). 我看到运行System.currentTimeMillis与(new Date())。getTime()只有一点点整体好处。

1 billion runs: (1000 outer loops, 1,000,000 inner loops):
    System.currentTimeMillis(): 14.353 seconds
    (new Date()).getTime(): 16.668 seconds

Individual runs would sometimes be slightly biased toward the later approach - depending on your system activity. 个别运行有时会稍微偏向后一种方法 - 取决于您的系统活动。

No difference, and Calendar.getTimeInMillis() is also same. 没有区别,Calendar.getTimeInMillis()也是一样的。 because the return results is the number of milliseconds since January 1, 1970, 00:00:00 GMT. 因为返回结果是自1970年1月1日00:00:00 GMT以来的毫秒数。 you will get a same long value whereever you are all over the word. 无论你是谁,你都将获得相同的长期价值。

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

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