我们可以在 node.js 中使用 process.hrtime() 作为 UUID 吗? [英] Can we use process.hrtime() as UUID in node.js?

查看:46
本文介绍了我们可以在 node.js 中使用 process.hrtime() 作为 UUID 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用 process.hrtime() 作为当前进程中的通用唯一 ID 吗?

Can we use process.hrtime() as universal unique id within the current process ?

var uuid = parseInt(process.hrtime().join(''));

推荐答案

您可以使用 process.hrtime() 来创建冲突几率低的标识符,但它们不是唯一的,尤其是跨应用程序重新启动(如果您将它们中的任何一个持久化到数据库或类似位置,这很重要),而不是涉及多个线程/进程/实例时.

You can use process.hrtime() to create identifiers with low chance of collision, but they are not unique, especially not across application restarts (which matters if you persist any of them to a database or similar), and not when several threads/processes/instances are involved.

来自文档:

这些时间相对于过去的任意时间,与一天中的时间无关

These times are relative to an arbitrary time in the past, and not related to the time of day

此外,通过使用 parseInt(....join('')),您引入了发生碰撞的第二种方式:例如[1, 23][12, 3] 将导致相同的结果.

Also, by using parseInt(....join('')), you are introducing a second way for collisions to happen: e.g. [1, 23] and [12, 3] will lead to the same result.

如果您想构建自己的解决方案(a[0] * 1e9 + a[1] 是一种天真的方法),您还应该了解 JavaScript 的精度限制数字——hrtime() 返回一个元组而不只是一个数字是有原因的.如有疑问,当您需要正确的 UUID 时,您可能应该使用正确的 UUID ;-)

If you want to build your own solution (a[0] * 1e9 + a[1] comes to mind as a naive approach), you should also be aware of the precision limits of JavaScript numbers -- there's a reason why hrtime() returns a tuple and not just a single number. When in doubt, when you need proper UUIDs, you should probably use proper UUIDs ;-)

这篇关于我们可以在 node.js 中使用 process.hrtime() 作为 UUID 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆