var timestamp = null;
timestamp = Date.now();
timestamp = new Date().getTime();
timestamp = performance.now()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Date.now() | |
new Date().getTime(); | |
performance.now() |
Test name | Executions per second |
---|---|
Date.now() | 9121435.0 Ops/sec |
new Date().getTime(); | 8116407.0 Ops/sec |
performance.now() | 5106809.5 Ops/sec |
This benchmark tests the performance of three different ways to get timestamps in JavaScript:
Date.now()
: A modern and generally recommended method for getting the number of milliseconds since the Unix epoch (January 1, 1970). It's built-in to all modern browsers.
new Date().getTime()
: An older method using the Date
object to get the timestamp. While it works, it can be less performant than Date.now()
.
performance.now()
: This method is part of the Performance API and provides high-resolution timestamps ideal for measuring short durations within a script. It's often considered more accurate and precise than the previous two options.
Pros and Cons:
Date.now()
:
new Date().getTime()
:
Date.now()
.Date.now()
and less precise.performance.now()
:
Date.now()
.Considerations:
Accuracy: If you need extremely precise timing measurements (e.g., for game development or scientific simulations), performance.now()
is generally the best choice.
Browser Support: Ensure that your target audience's browsers support the methods you use. Date.now()
and new Date().getTime()
are more widely supported.
Performance: For most general-purpose tasks, Date.now()
often provides sufficient performance. If speed is critical, benchmark all options to see which performs best in your specific context.
Alternatives:
While these three methods are commonly used for timestamps, other libraries or APIs might exist depending on the specific use case (e.g., specialized high-performance timing libraries).