Skip to content

Commit e156415

Browse files
authored
feat: optimize V8 performance of bytesToUuid (#434)
1 parent f6ce4bf commit e156415

File tree

2 files changed

+30
-24
lines changed

2 files changed

+30
-24
lines changed

examples/benchmark/benchmark.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@ const uuidv5 = (typeof window !== 'undefined' && window.uuidv5) || require('uuid
99
console.log('Starting. Tests take ~1 minute to run ...');
1010

1111
const array = new Array(16);
12-
const suite = new Benchmark.Suite();
12+
13+
const suite = new Benchmark.Suite({
14+
onError(event) {
15+
console.error(event.target.error);
16+
},
17+
});
1318

1419
suite
1520
.add('uuidv1()', function () {

src/bytesToUuid.js

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,30 @@ function bytesToUuid(buf, offset) {
1313

1414
const bth = byteToHex;
1515

16-
// join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
17-
return [
18-
bth[buf[i + 0]],
19-
bth[buf[i + 1]],
20-
bth[buf[i + 2]],
21-
bth[buf[i + 3]],
22-
'-',
23-
bth[buf[i + 4]],
24-
bth[buf[i + 5]],
25-
'-',
26-
bth[buf[i + 6]],
27-
bth[buf[i + 7]],
28-
'-',
29-
bth[buf[i + 8]],
30-
bth[buf[i + 9]],
31-
'-',
32-
bth[buf[i + 10]],
33-
bth[buf[i + 11]],
34-
bth[buf[i + 12]],
35-
bth[buf[i + 13]],
36-
bth[buf[i + 14]],
37-
bth[buf[i + 15]],
38-
].join('');
16+
// Note: Be careful editing this code! It's been tuned for performance
17+
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
18+
return (
19+
bth[buf[i + 0]] +
20+
bth[buf[i + 1]] +
21+
bth[buf[i + 2]] +
22+
bth[buf[i + 3]] +
23+
'-' +
24+
bth[buf[i + 4]] +
25+
bth[buf[i + 5]] +
26+
'-' +
27+
bth[buf[i + 6]] +
28+
bth[buf[i + 7]] +
29+
'-' +
30+
bth[buf[i + 8]] +
31+
bth[buf[i + 9]] +
32+
'-' +
33+
bth[buf[i + 10]] +
34+
bth[buf[i + 11]] +
35+
bth[buf[i + 12]] +
36+
bth[buf[i + 13]] +
37+
bth[buf[i + 14]] +
38+
bth[buf[i + 15]]
39+
).toLowerCase();
3940
}
4041

4142
export default bytesToUuid;

0 commit comments

Comments
 (0)