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.
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.
Also, if the timestamp is obtained for anything other than timestamping the data, for example, the timing of code execution, it is always a good idea to think if the same can be achieved via setTimeout or setInterval calls instead, without direct access to timestamp value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With