Performance - Date.now() vs Date.getTime()

Javascript

Javascript Problem Overview


var timeInMs = Date.now();

per MDN

vs.

var timeInMs = new Date(optional).getTime();

per MDN.

Is there any difference between the two, besides the syntax and the ability to set the Date (to not the current) via optional in the second version?

Date.now() is faster - check out the jsperf

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;

http://jsperf.com/new-date-vs-settime

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser656925View Question on Stackoverflow
Solution 1 - JavascriptPointyView Answer on Stackoverflow
Solution 2 - JavascriptjonvuriView Answer on Stackoverflow
Solution 3 - JavascriptGregory MagarshakView Answer on Stackoverflow
Solution 4 - JavascriptBrett ZamirView Answer on Stackoverflow
Solution 5 - JavascriptSashaKView Answer on Stackoverflow