Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(NODE-4194): improve objectId constructor performance #498

Merged
merged 9 commits into from
May 5, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ coverage/
*.d.ts
*.tgz
docs/public

*.0x
83 changes: 83 additions & 0 deletions etc/benchmarks/main.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { performance } from 'perf_hooks';
import { readFile } from 'fs/promises';

const readJSONFile = async path =>
JSON.parse(await readFile(new URL(path, import.meta.url), { encoding: 'utf8' }));

const ITERATIONS = 10_000;

function average(array) {
let sum = 0;
for (const value of array) sum += value;
return sum / array.length;
}

function testPerformance(fn, iterations = ITERATIONS) {
let measurements = [];
for (let i = 0; i < iterations; i++) {
const start = performance.now();
fn(i);
const end = performance.now();
measurements.push(end - start);
}
return average(measurements).toFixed(8);
}

async function main() {
const [currentBSON, currentReleaseBSON, legacyBSONLib] = await Promise.all([
(async () => ({
lib: await import('../../lib/bson.js'),
version: 'current local'
}))(),
(async () => ({
lib: await import('../../node_modules/bson_latest/lib/bson.js'),
version: (await readJSONFile('../../node_modules/bson_latest/package.json')).version
}))(),
(async () => {
const legacyBSON = (await import('../../node_modules/bson_legacy/index.js')).default;
return {
lib: { ...legacyBSON, ...legacyBSON.prototype },
version: (await readJSONFile('../../node_modules/bson_legacy/package.json')).version
};
})()
]).catch(error => {
console.error(error);
console.error(
`Please run:\n${[
'npm run build',
'npm install --no-save bson_legacy@npm:bson@1 bson_latest@npm:bson@latest'
].join('\n')}`
);
process.exit(1);
});

const documents = Array.from({ length: ITERATIONS }, () =>
currentReleaseBSON.lib.serialize({
_id: new currentReleaseBSON.lib.ObjectId(),
field1: 'value1'
})
);

console.log(`\nIterations: ${ITERATIONS}`);

for (const bson of [currentBSON, currentReleaseBSON, legacyBSONLib]) {
console.log(`\nBSON@${bson.version}`);
console.log(
`deserialize({ oid, string }, { validation: { utf8: false } }) takes ${testPerformance(i =>
bson.lib.deserialize(documents[i], { validation: { utf8: false } })
)}ms on average`
);

const oidBuffer = Buffer.from('00'.repeat(12), 'hex');
console.log(
`new Oid(buf) take ${testPerformance(() => new bson.lib.ObjectId(oidBuffer))}ms on average`
);
}

console.log();
}

main()
.then(() => null)
.catch(error => console.error(error));
140 changes: 70 additions & 70 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions src/ensure_buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import { isAnyArrayBuffer } from './parser/utils';
* @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in
*/
export function ensureBuffer(potentialBuffer: Buffer | ArrayBufferView | ArrayBuffer): Buffer {
if (potentialBuffer instanceof Buffer) {
addaleax marked this conversation as resolved.
Show resolved Hide resolved
durran marked this conversation as resolved.
Show resolved Hide resolved
return potentialBuffer;
}

if (ArrayBuffer.isView(potentialBuffer)) {
return Buffer.from(
potentialBuffer.buffer,
Expand Down
2 changes: 1 addition & 1 deletion src/objectid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class ObjectId {
// Generate a new id
this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
} else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
this[kId] = ensureBuffer(workingId);
this[kId] = workingId instanceof Buffer ? workingId : ensureBuffer(workingId);
addaleax marked this conversation as resolved.
Show resolved Hide resolved
} else if (typeof workingId === 'string') {
if (workingId.length === 12) {
const bytes = Buffer.from(workingId);
Expand Down
13 changes: 13 additions & 0 deletions test/node/ensure_buffer_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ describe('ensureBuffer tests', function () {
expect(ensureBuffer).to.be.a('function');
});

it('should return the same instance if a buffer is passed in', function () {
const inBuffer = Buffer.from('00'.repeat(12), 'hex');

const outBuffer = ensureBuffer(inBuffer);

// instance equality
expect(inBuffer).to.equal(outBuffer);
// deep equality
expect(inBuffer).to.deep.equal(outBuffer);
// class method equality
expect(Buffer.prototype.equals.call(inBuffer, outBuffer)).to.be.true;
});

it('should return a view over the exact same memory when a Buffer is passed in', function () {
const bufferIn = Buffer.alloc(10);
let bufferOut;
Expand Down
2 changes: 2 additions & 0 deletions test/node/object_id_tests.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* globals performance */
'use strict';

const Buffer = require('buffer').Buffer;
Expand All @@ -6,6 +7,7 @@ const BSONTypeError = BSON.BSONTypeError;
const ObjectId = BSON.ObjectId;
const util = require('util');
const getSymbolFrom = require('./tools/utils').getSymbolFrom;
const getGlobal = require('./tools/utils').getGlobal;

describe('ObjectId', function () {
it('should correctly handle objectId timestamps', function (done) {
Expand Down
19 changes: 19 additions & 0 deletions test/node/tools/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* globals globalThis window self */
'use strict';

exports.assertArrayEqual = function (array1, array2) {
Expand Down Expand Up @@ -172,3 +173,21 @@ const getSymbolFrom = function (target, symbolName, assertExists) {
};

exports.getSymbolFrom = getSymbolFrom;

function checkForMath(potentialGlobal) {
// eslint-disable-next-line eqeqeq
return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal;
}

// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
function getGlobal() {
// eslint-disable-next-line no-undef
return (
checkForMath(typeof globalThis === 'object' && globalThis) ||
checkForMath(typeof window === 'object' && window) ||
checkForMath(typeof self === 'object' && self) ||
checkForMath(typeof global === 'object' && global) ||
Function('return this')()
);
}
exports.getGlobal = getGlobal;