Home java Which is faster, System.currentTimeMillis () or Date (). getTime ()?

Which is faster, System.currentTimeMillis () or Date (). getTime ()?

Author

Date

Category

Which is faster – System.currentTimeMillis () or Date (). getTime () ?


Answer 1, authority 100%

System.currentTimeMillis () is slightly faster than Date (). GetTime () :

long t = System.currentTimeMillis ();
for (int i = 0; i & lt; 1000000000; i ++) {
  System.currentTimeMillis ();
}
System.out.println ("Elapsed:" + (System.currentTimeMillis () - t));
t = System.currentTimeMillis ();
for (int i = 0; i & lt; 1000000000; i ++) {
  new Date (). getTime ();
}
System.out.println ("Elapsed:" + (System.currentTimeMillis () - t));

Result:

Elapsed: 11623
Elapsed: 11713

And the reason for this is very simple, if you look at sources , then you can see that the Date constructor calls System.currentTimeMillis () (about this wrote here ):

public Date () {
  this (System.currentTimeMillis ());
}

Answer 2, authority 93%

In theory, System.currentTimeMillis () will be faster by not creating a new new Date () object that still calls System.currentTimeMillis ( ) , but the difference will be negligible.


Answer 3, authority 67%

System.currentTimeMillis () is faster, simply because new Date () calls the function itself. You can see this in the implementation for OpenJDK . You can also see a similar SOen question .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions