编辑
为了快速将字符串转换为唯一ID,请改用crypto.createHash()。对于给定的字符串输入,结果将是相同的。
您可以使用 MD5 或 SHA256,因为两者都需要相同的时间,计算 100 万个唯一 ID 平均需要 2.2 秒。
代码如下:
const crypto = require('crypto');
function uniqueId(string, algorithm = 'md5') {
return crypto.createHash(algorithm).update(string).digest('hex');
}
console.log('started');
console.time('generateIDsMD5')
for (let i = 0; i < 1000000; i++) {
uniqueId('a string ' + i);
}
console.timeEnd('generateIDsMD5');
console.time('generateIDsSHA256')
for (let i = 0; i < 1000000; i++) {
uniqueId('a string ' + i, 'sha256');
}
console.timeEnd('generateIDsSHA256');
// For instance, It will take around 2.2s average
// to generate 1Million Unique IDs with MD5 or SHA256 encryption
console.log('MD5 string ', uniqueId('a string ' + 1));
console.log('MD5 sameString ', uniqueId('a string ' + 2));
console.log('MD5 sameString ', uniqueId('a string ' + 2));
console.log('SHA256 string ', uniqueId('a string ' + 1, 'sha256'));
console.log('SHA256 sameString ', uniqueId('a string ' + 2, 'sha256'));
console.log('SHA256 sameString ', uniqueId('a string ' + 2, 'sha256'));
console.log('finished');
以前的答案
我改编了 Firebase 中的代码,并为您提供了一些自定义测试,直接在您的 node.js 上可用。 100 万个 ID 最多需要 3 秒,而 100.000 个 ID 只需 300 毫秒,这是您考虑的日常使用方法。
这使用crypto 如果在 node.js 环境中运行被认为是非常安全的。
这里是使用示例包装的函数:
const crypto = require('crypto');
function autoId(bytesLength) {
const chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let autoId = '';
while (autoId.length < bytesLength) {
const bytes = crypto.randomBytes(40);
bytes.forEach(b => {
// Length of `chars` is 62. We only take bytes between 0 and 62*4-1
// (both inclusive). The value is then evenly mapped to indices of `char`
// via a modulo operation.
const maxValue = 62 * 4 - 1;
if (autoId.length < bytesLength && b <= maxValue) {
autoId += chars.charAt(b % 62);
}
});
}
return autoId;
}
console.log('started');
console.time('generateIDs')
for (let i = 0; i < 1000000; i++) {
autoId(20);
}
console.timeEnd('generateIDs');
// For instance, It will take around 3s average
// to generate 1 Million Unique IDs with 20 bytes length
console.log('example 20bytes ', autoId(20));
console.log('example 40bytes ', autoId(40));
console.log('example 60bytes ', autoId(60));
console.log('finished');
只需使用node thisfile.js,您就会看到结果。
由于firebase主要是开源的,我们可以在这里找到node.js中使用的官方uniqueId生成器来生成ID:https://github.com/googleapis/nodejs-firestore/blob/4f4574afaa8cf817d06b5965492791c2eff01ed5/dev/src/util.ts#L52
重要
如果您要加入 2 个 ID,请不要使用任何斜线 /,因为您知道这是不允许的,而是使用下划线 _ 或什么都不使用,因为您可以控制 ID 的长度,因此您应该知道如何相应地拆分 ID(例如 40 个字节包含 2 个 20 字节的 ID)。
文档 ID 中的 firestore 限制为 1500 字节,因此您有很多可玩的地方。
更多信息:https://firebase.google.com/docs/firestore/quotas#limits