Skip to content

Commit

Permalink
feat: optimize V8 performance of bytesToUuid (#434)
Browse files Browse the repository at this point in the history
  • Loading branch information
awwit authored May 4, 2020
1 parent f6ce4bf commit e156415
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 24 deletions.
7 changes: 6 additions & 1 deletion examples/benchmark/benchmark.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ const uuidv5 = (typeof window !== 'undefined' && window.uuidv5) || require('uuid
console.log('Starting. Tests take ~1 minute to run ...');

const array = new Array(16);
const suite = new Benchmark.Suite();

const suite = new Benchmark.Suite({
onError(event) {
console.error(event.target.error);
},
});

suite
.add('uuidv1()', function () {
Expand Down
47 changes: 24 additions & 23 deletions src/bytesToUuid.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,30 @@ function bytesToUuid(buf, offset) {

const bth = byteToHex;

// join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
return [
bth[buf[i + 0]],
bth[buf[i + 1]],
bth[buf[i + 2]],
bth[buf[i + 3]],
'-',
bth[buf[i + 4]],
bth[buf[i + 5]],
'-',
bth[buf[i + 6]],
bth[buf[i + 7]],
'-',
bth[buf[i + 8]],
bth[buf[i + 9]],
'-',
bth[buf[i + 10]],
bth[buf[i + 11]],
bth[buf[i + 12]],
bth[buf[i + 13]],
bth[buf[i + 14]],
bth[buf[i + 15]],
].join('');
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
return (
bth[buf[i + 0]] +
bth[buf[i + 1]] +
bth[buf[i + 2]] +
bth[buf[i + 3]] +
'-' +
bth[buf[i + 4]] +
bth[buf[i + 5]] +
'-' +
bth[buf[i + 6]] +
bth[buf[i + 7]] +
'-' +
bth[buf[i + 8]] +
bth[buf[i + 9]] +
'-' +
bth[buf[i + 10]] +
bth[buf[i + 11]] +
bth[buf[i + 12]] +
bth[buf[i + 13]] +
bth[buf[i + 14]] +
bth[buf[i + 15]]
).toLowerCase();
}

export default bytesToUuid;

0 comments on commit e156415

Please sign in to comment.