From 81c8fa1857304634ce7d0b61ca22d0335e3b1fb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Boquet?= Date: Fri, 8 Sep 2023 21:50:14 +0200 Subject: [PATCH] fix(NODE-5577): improve ObjectId serialization by around 10% (#614) Co-authored-by: Warren James --- src/parser/serializer.ts | 10 +++++--- test/bench/src/index.ts | 3 ++- .../src/suites/objectid_serialization.ts | 24 +++++++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 test/bench/src/suites/objectid_serialization.ts diff --git a/src/parser/serializer.ts b/src/parser/serializer.ts index 6f75cb0a..f5f56226 100644 --- a/src/parser/serializer.ts +++ b/src/parser/serializer.ts @@ -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) { diff --git a/test/bench/src/index.ts b/test/bench/src/index.ts index 2de638aa..81103404 100644 --- a/test/bench/src/index.ts +++ b/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'; @@ -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); } diff --git a/test/bench/src/suites/objectid_serialization.ts b/test/bench/src/suites/objectid_serialization.ts new file mode 100644 index 00000000..ef62301e --- /dev/null +++ b/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; +}