简体   繁体   中英

What is faster? System.currentTimeMillis() or Date().getTime()?

What is faster method?

System.currentTimeMillis() 

or

new Date().getTime()?

Is there the faster solution to know elapsed time?

If you do

new Date()

it calls

/**
 * 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());
}

so it calls System.currentTimeMillis() AND creates an object you immediately throw away.

If you are very lucky, escape analysis will remove the redundant object and the performance will be much the same.

However, I wouldn't assume Escape Analysis will kick in and just call

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

Notes:

  • object creation is fast, and even though it's redundant, a Date object is small and cheap to create. However it contributes to a) the number of objects in your system and b) general noise in your test if you try to memory profile it. To reduce variation (and speed up your code) you want to reduce memory allocations, esp redundant ones.
  • this is only accurate to 1 ms and if your system corrects the time while this is running, it can be incorrect (even negative) However, it rarely does this in a dramatic fashion, and instead corrects the clock gradually meaning the time might be out by a small percentage. Given the variation in time due to other things happening on the system, you would be very lucky if this was you biggest problem.
  • System.nanoTime() could be used instead but this can have a drift of it's own. Over a longer period of time eg hours, System.currentTimeMillis() can be more accurate.
  • if you are trying to write a micro-benchmark, I would ensure the code is warmed up. ie ignore the first 2 - 10 seconds as there is a good chance the code isn't warm at this stage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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