There are different ways to get the current time in milliseconds with Date
object:
(new Date()).getTime(); +new Date(); Date.now();
Assuming that you don’t need to create an object and just need a current time in milliseconds, which one would be the most effective one? In terms of performance.
EDIT: I understand most devs wouldn’t care about this, but it may matter when you work in a low-tech embedded environment or just to kill the curiosity.
Advertisement
Answer
Date.now()
wins. See jsperf.com test
But as noted in comments above, the CPU cost is likely uninteresting compared to just about anything else you’ll be doing.
@techfoobar mentions the cost of allocating Date objects (or, really, the cost of garbage collecting those Date objects). That may or may not be a significant win, as Date.now() is probably allocating Number objects, which would be about as expensive.