Nodejs:正常字符串,base64字符串和缓冲区比较中UUID之间的巨大性能差异

时间:2016-07-17 06:32:31

标签: node.js string base64 buffer

结果:

true
base64: 35.758ms
true
string: 12.811ms
true
buffer: 127.691ms

代码:

let n = 1000000;

let uuid = require("node-uuid");

let uuidaString = uuid.v4(),
    uuidbString = uuidaString.slice(0),

    uuidaBuffer = uuid.parse(uuidaString, new Buffer(16)),
    uuidbBuffer = uuid.parse(uuidbString, new Buffer(16)),

    uuidaBase64 = uuidaBuffer.toString("base64"),
    uuidbBase64 = uuidbBuffer.toString("base64");

console.log(uuidaBase64 === uuidbBase64);
console.time("base64");
for (let i = 0; i < n && uuidaBase64 === uuidbBase64; i++) {

}
console.timeEnd("base64");

console.log(uuidaString === uuidbString);
console.time("string");
for (let i = 0; i < n && uuidaString === uuidbString; i++) {

}
console.timeEnd("string");


console.log(Buffer.compare(uuidaBuffer, uuidbBuffer) === 0);
console.time("buffer");
for (let i = 0; i < n && Buffer.compare(uuidaBuffer, uuidbBuffer) === 0; i++) {

}
console.timeEnd("buffer");

有人解释结果吗?我希望正常的字符串比较是最慢的,但它显示最快。除此之外,我希望base64字符串比较比普通字符串比较更快,因为base64字符串比普通字符串短。这是一个错误吗?

1 个答案:

答案 0 :(得分:0)

请尝试使用此功能:

uuidbBase64 = uuidaBase64.slice(0)

当我这样做时,我看到常规字符串与base64字符串几乎完全相同。

也许.slice(0)只返回相同的对象,所以不必逐个字符地进行比较?