Performance - Date.now() vs Date.getTime()
JavascriptJavascript Problem Overview
Javascript Solutions
Solution 1 - Javascript
These things are the same (edit semantically; performance is a little better with .now()
):
var t1 = Date.now();
var t2 = new Date().getTime();
However, the time value from any already-created Date
instance is frozen at the time of its construction (or at whatever time/date it's been set to). That is, if you do this:
var now = new Date();
and then wait a while, a subsequent call to now.getTime()
will tell the time at the point the variable was set.
Solution 2 - Javascript
They are effectively equivalent, but you should use Date.now()
. It's clearer and about twice as fast.
Edit: Source: http://jsperf.com/date-now-vs-new-date
Solution 3 - Javascript
When you do (new Date()).getTime()
you are creating a new Date object. If you do this repeatedly, it will be about 2x slower than Date.now()
The same principle should apply for Array.prototype.slice.call(arguments, 0)
vs [].slice.call(arguments, 0)
Solution 4 - Javascript
Yes, that is correct; they are effectively equivalent when using the current time.
Solution 5 - Javascript
Sometimes it's preferable to keep some time tracking variable in a Date object format rather than as just a number of milliseconds, to have access to Date's methods without re-instantiating. In that case, Date.now() still wins over new Date() or the like, though only by about 20% on my Chrome and by a tiny amount on IE.
See my JSPERF on
timeStamp2.setTime(Date.now()); // set to current;
vs.
timeStamp1 = new Date(); // set to current;