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 .