Skip to content

Commit 81c8fa1

Browse files
billouboqW-A-James
andauthored
fix(NODE-5577): improve ObjectId serialization by around 10% (#614)
Co-authored-by: Warren James <[email protected]>
1 parent 6fee2d5 commit 81c8fa1

File tree

3 files changed

+33
-4
lines changed

3 files changed

+33
-4
lines changed

src/parser/serializer.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -257,14 +257,18 @@ function serializeObjectId(buffer: Uint8Array, key: string, value: ObjectId, ind
257257
buffer[index++] = 0;
258258

259259
// Write the objectId into the shared buffer
260-
if (isUint8Array(value.id)) {
261-
buffer.set(value.id.subarray(0, 12), index);
260+
const idValue = value.id;
261+
262+
if (isUint8Array(idValue)) {
263+
for (let i = 0; i < 12; i++) {
264+
buffer[index++] = idValue[i];
265+
}
262266
} else {
263267
throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
264268
}
265269

266270
// Adjust index
267-
return index + 12;
271+
return index;
268272
}
269273

270274
function serializeBuffer(buffer: Uint8Array, key: string, value: Uint8Array, index: number) {

test/bench/src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { getStringDeserializationSuite } from './suites/string_deserialization';
2+
import { getObjectIdSerializationSuite } from './suites/objectid_serialization';
23
import { type PerfSendData } from './util';
34
import { writeFile } from 'fs';
45
import { cpus, totalmem } from 'os';
@@ -17,7 +18,7 @@ console.log(
1718
].join('\n')
1819
);
1920

20-
for (const suite of [getStringDeserializationSuite()]) {
21+
for (const suite of [getStringDeserializationSuite(), getObjectIdSerializationSuite()]) {
2122
suite.run();
2223
results.push(suite.results);
2324
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { Suite } from '../suite';
2+
import * as BSON from '../../../../';
3+
4+
export function getObjectIdSerializationSuite(): Suite {
5+
const suite = new Suite('objectid serialization');
6+
const data = {
7+
docs: Array.from({ length: 1_000 }, () => new BSON.ObjectId())
8+
};
9+
10+
suite.task({
11+
name: 'ObjectId serialization',
12+
data,
13+
fn: objectIds => {
14+
BSON.serialize(objectIds);
15+
},
16+
iterations: 10_000,
17+
resultUnit: 'megabytes_per_second',
18+
transform: (runtimeMS: number) => {
19+
return BSON.calculateObjectSize(data) / 1024 ** 2 / (runtimeMS / 1000);
20+
}
21+
});
22+
23+
return suite;
24+
}

0 commit comments

Comments
 (0)