Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest and lightest way to get the current time in milliseconds with JS Date object

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.

like image 330
Sherzod Avatar asked Nov 27 '13 03:11

Sherzod


2 Answers

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.

like image 181
broofa Avatar answered Sep 23 '22 11:09

broofa


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.

like image 38
Dmitriy Avatar answered Sep 22 '22 11:09

Dmitriy