Java 什么更快?System.currentTimeMillis()或Date().getTime()?

Java 什么更快?System.currentTimeMillis()或Date().getTime()?,java,garbage-collection,Java,Garbage Collection,什么是更快的方法 System.currentTimeMillis() 或 是否有更快的解决方案来了解运行时间?如果有 new Date() 它叫 /** * Allocates a <code>Date</code> object and initializes it so that * it represents the time at which it was allocated, measured to the * nearest millisecon

什么是更快的方法

System.currentTimeMillis() 

是否有更快的解决方案来了解运行时间?

如果有

new Date()
它叫

/**
 * Allocates a <code>Date</code> object and initializes it so that
 * it represents the time at which it was allocated, measured to the
 * nearest millisecond.
 *
 * @see     java.lang.System#currentTimeMillis()
 */
public Date() {
    this(System.currentTimeMillis());
}
因此,它调用System.currentTimeMillis()并创建一个您立即丢弃的对象

如果您非常幸运,escape分析将删除冗余对象,性能也将大致相同

然而,我不认为逃逸分析会起作用,只是打电话

long start = System.currentTimeMillis();
// do something
long time = System.currentTimeMillis() - start;
注:

  • 对象创建速度很快,即使是冗余的,日期对象也很小,创建成本也很低。但是,如果您尝试对其进行内存配置,它会导致a)系统中对象的数量和b)测试中的一般噪声。为了减少变化(并加速代码),您需要减少内存分配,特别是冗余内存分配
  • 这只精确到1毫秒,如果您的系统在运行时更正时间,则可能不正确(甚至是负数)。但是,它很少以戏剧性的方式执行此操作,而是逐渐更正时钟,这意味着时间可能会减少一小部分。考虑到系统上发生的其他事情在时间上的变化,如果这是您最大的问题,您将非常幸运
  • 可以改为使用System.nanoTime(),但这可能有其自身的问题。在较长的时间段(如小时)内,System.currentTimeMillis()可以更精确
  • 如果您正试图编写一个微基准测试,我会确保代码已预热。i、 忽略前2-10秒,因为在这个阶段代码很有可能不热

你说的更快是什么意思?在更少的CPU周期中?为什么这很重要?虽然有一种更精确的方法是使用
System.nanoTime()
,但您仍然需要得到两次,然后自己计算经过的时间。请参阅。我使用的是
long now=System.currentTimeMillis();long elapsedTime=现在-上一次
由于调用了
System.currentTimeMillis()
,因此直接调用
System.currentTimeMillis()
的工作量似乎比较少(例如,它不创建对象,不需要额外的方法调用),因此人们希望它“更快”。但是,这不是测量运行时间的正确方法。@而且,如果系统中的一点时钟漂移是导致变化/抖动的最大原因,那么您将非常幸运。到目前为止,不预热代码是最常见的问题。
long start = System.currentTimeMillis();
// do something
long time = System.currentTimeMillis() - start;