11

我希望从对返回时间戳的函数的多次调用中获得微小的性能提升。该函数如下所示:

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

我可以将其替换为:

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

我知道 Date 在内部使用 System.currentTimeMillis()。我的问题更多的是夏令时或时区是否会导致这两种方法的结果不同。我想这可能会出现 Calendar 对象,但不会出现 Date 对象,但希望对此进行一些澄清。

我知道我可能不会在实际应用程序中看到明显的性能差异,但仍然想知道答案。

谢谢!

4

3 回答 3

12

没有区别,除了分配 Date 对象引起的非常轻微的延迟。

javadoc的默认构造函数Date

分配一个 Date 对象并对其进行初始化,以便它表示分配它的时间,精确到毫秒。

ADate只是纪元毫秒的一个薄包装,没有任何时区概念。仅当呈现为 String 时才考虑时区,但这由Locale类处理。

于 2013-06-08T21:49:27.707 回答
3

我建议运行一个单元测试(例如https://gist.github.com/ledlogic/8532028)。我看到运行 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

个别运行有时会稍微偏向于后一种方法 - 取决于您的系统活动。

于 2014-01-21T00:17:11.167 回答
2

No difference, and Calendar.getTimeInMillis() is also same. because the return results is the number of milliseconds since January 1, 1970, 00:00:00 GMT. you will get a same long value whereever you are all over the word.

于 2014-10-30T03:57:48.423 回答