WooD WooD - 4 months ago 43
Node.js Question

Nodejs: Huge performance difference among UUID in normal string, base64 string and Buffer comparison

Result:

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


Code:

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");


Does anybody explain the result? I would expect normal string comparison would be the slowest but it shows the fastest. Other than that I would expect base64 string comparison would be faster than normal string comparison because base64 string is shorter than normal string. Is it a bug?

Answer

Try with this instead:

uuidbBase64 = uuidaBase64.slice(0)

When I do that, I see nearly identical times for regular strings versus base64 strings.

Perhaps .slice(0) just returns the same object, so it doesn't have to be compared character by character?

Comments