Skip to content

Commit

Permalink
fix(NODE-5577): improve ObjectId serialization by around 10% (#614)
Browse files Browse the repository at this point in the history
Co-authored-by: Warren James <warren.james@mongodb.com>
  • Loading branch information
billouboq and W-A-James committed Sep 8, 2023
1 parent 6fee2d5 commit 81c8fa1
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
10 changes: 7 additions & 3 deletions src/parser/serializer.ts
Expand Up @@ -257,14 +257,18 @@ function serializeObjectId(buffer: Uint8Array, key: string, value: ObjectId, ind
buffer[index++] = 0;

// Write the objectId into the shared buffer
if (isUint8Array(value.id)) {
buffer.set(value.id.subarray(0, 12), index);
const idValue = value.id;

if (isUint8Array(idValue)) {
for (let i = 0; i < 12; i++) {
buffer[index++] = idValue[i];
}
} else {
throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
}

// Adjust index
return index + 12;
return index;
}

function serializeBuffer(buffer: Uint8Array, key: string, value: Uint8Array, index: number) {
Expand Down
3 changes: 2 additions & 1 deletion test/bench/src/index.ts
@@ -1,4 +1,5 @@
import { getStringDeserializationSuite } from './suites/string_deserialization';
import { getObjectIdSerializationSuite } from './suites/objectid_serialization';
import { type PerfSendData } from './util';
import { writeFile } from 'fs';
import { cpus, totalmem } from 'os';
Expand All @@ -17,7 +18,7 @@ console.log(
].join('\n')
);

for (const suite of [getStringDeserializationSuite()]) {
for (const suite of [getStringDeserializationSuite(), getObjectIdSerializationSuite()]) {
suite.run();
results.push(suite.results);
}
Expand Down
24 changes: 24 additions & 0 deletions test/bench/src/suites/objectid_serialization.ts
@@ -0,0 +1,24 @@
import { Suite } from '../suite';
import * as BSON from '../../../../';

export function getObjectIdSerializationSuite(): Suite {
const suite = new Suite('objectid serialization');
const data = {
docs: Array.from({ length: 1_000 }, () => new BSON.ObjectId())
};

suite.task({
name: 'ObjectId serialization',
data,
fn: objectIds => {
BSON.serialize(objectIds);
},
iterations: 10_000,
resultUnit: 'megabytes_per_second',
transform: (runtimeMS: number) => {
return BSON.calculateObjectSize(data) / 1024 ** 2 / (runtimeMS / 1000);
}
});

return suite;
}

0 comments on commit 81c8fa1

Please sign in to comment.