Reputation:
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
Upvotes: 168
Views: 128772
Reputation: 5920
They are effectively equivalent, but you should use Date.now()
. It's clearer and about twice as fast.
Edit: Source: https://jsperf.app/nimime/15
Upvotes: 83
Reputation: 69
Date.now() call the static method and this is enough to be preferred, perfoming a test:
# cat test.ts
const limit = 10000000 //ten milion
let startTime = Date.now()
let val = 0
for (let i=0; i<=limit; i++) {
const val1 = Date.now()
}
let diff = Date.now() - startTime
console.log('Time Date.now(): ' + diff + ' ms')
startTime = Date.now()
val=0
for (let i=0; i<=limit; i++) {
const val1 = new Date().getTime()
}
diff = Date.now() - startTime
console.log('Time with new Date().getTime: ' + diff + ' ms' )
Test execution:
# node test.ts
Time Date.now(): 818 ms
Time with new Date().getTime: 1625 ms
Date.now() is 50% faster
Upvotes: 1
Reputation: 1
Date.now()
is calling the static method now()
of the class Date
.
While new Date().getTime()
can be divided into two steps:
new Date()
: Call the constructor()
method of Date
class to initialize an instance of Date
class.getTime()
method of the instance we just initialize.MDN web docs classifies Date.now()
into static method of Date
, and Date.prototype.getTime()
into instance method.
Upvotes: -2
Reputation: 165
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
Upvotes: 3
Reputation: 413720
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.
Upvotes: 148
Reputation: 2039
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)
Upvotes: 6
Reputation: 14345
Yes, that is correct; they are effectively equivalent when using the current time.
Upvotes: 2