Which is faster? System.currentTimeMillis () or Date (). Gettime ()?

What is a faster method?

System.currentTimeMillis() 

or

new Date().getTime()?

Is there a faster solution to know the elapsed time?

+4
source share
1 answer

If you do

new Date()

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

therefore, it calls System.currentTimeMillis () and creates an object that you immediately throw away.

If you're very lucky, an escape analysis will remove the redundant object, and performance will be pretty much the same.

However, I would not have expected Escape Analysis to come out and just call

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

Notes:

  • , , Date . : ) ) , . ( ), , esp .
  • 1 , , , ( ). , , . - , , , .
  • System.nanoTime() , . , . , System.currentTimeMillis() .
  • -, , . 2 - 10 , , .
+9

All Articles