var timedif = null;
timedif = Date.now() - Date.now();
timedif = new Date() - new Date();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Date.now() | |
new Date().getTime(); |
Test name | Executions per second |
---|---|
Date.now() | 5486806.0 Ops/sec |
new Date().getTime(); | 2385763.5 Ops/sec |
This benchmark on MeasureThat.net compares the performance of two methods for calculating the time difference in JavaScript:
Date.now()
: This method returns the number of milliseconds that have elapsed since the Unix epoch (January 1, 1970, 00:00:00 UTC). new Date().getTime()
: This creates a new Date
object and then uses its .getTime()
method to get the number of milliseconds since the Unix epoch.Breakdown:
The benchmark code essentially performs these actions in both test cases:
timedif = null;
is used to store the calculated time difference.timedif = Date.now() - Date.now();
This calculates the difference between the current time and itself, always resulting in 0.timedif = new Date() - new Date();
This creates two new Date
objects and subtracts their timestamps.Pros & Cons:
Date.now()
:
new Date().getTime()
:
Date
object methods for manipulating and formatting the timestamp (e.g., getting year, month, day, etc.).Date.now()
, as it involves creating a new Date
object and then calling .getTime()
Other Considerations:
This benchmark highlights that Date.now()
is significantly faster for simple time difference calculations in JavaScript.
Let me know if you have any more questions about this or other benchmarks!