Say you have an array of data entries and you need to attach a unique identifier to each entry. The popular approach would be use Date.now() as a unique identifier. The problem with this approach is that there is a chance of two or more entries having the same identifier. This is because the timestamps returned by Date.now() have a resolution of one-millisecond. Thus it is highly probably that you could have collisions between the unique identifiers of the data entries. Let us consider the following example that loops 5 times, printing out a Date.now() timestamp every loop. Let's open up our command prompt and let's run the following code in node (to enter node just type the word node in your command prompt assuming that you already have it in your environment).
CODE:
for (let index = 0; index < 5; index++) {
console.log(Date.now())
}
OUTPUT:
1691741535783
1691741535784
1691741535785 < Identical
1691741535785 < Identical
1691741535785 < Identical
As you can see in the output that the last three outputs were the same, so if you where using these as unique identifiers you would have collisions.
Enter performance.now()
Unlike Date.now() the timestamps returned by performance.now() represent floating point numbers with a resolution of up to 5 microsecond rather than the one-millisecond resolution of Date.now() timestamps. Also performance.now() timestamps always increase at a constant rate being independent of the system clock which can be manually adjusted or susceptible to change by software such as the Network Time Protocol. Lets see the same example that we did above but this time with performance.now().
CODE:
for (let index = 0; index < 5; index++) {
console.log(performance.now())
}
OUTPUT:
7908.96749997139
7910.144699931145
7910.284399986267
7910.412899971008
7910.533899903297
Let's test performance.now() further by logging two timestamps at the same time.
CODE:
console.log(`${ performance.now() } ${ performance.now() }`)
OUTPUT:
773756.6698999405 773756.6811999083
As you can see that even when you log it at the same time the timestamps are different thus there is no chance of collisions occurring. I highly recommend that you take a look at the MDN docs for performance.now() if you want to read more about it (https://developer.mozilla.org/en-US/docs/Web/API/Performance/now).
Top comments (3)
Cool! Didn’t know that! Thanks 🙏
This is quite helpful...
I am glad you found it helpful