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-6344): Improve ObjectId.isValid(string) performance #708

Merged
merged 3 commits into from
Sep 17, 2024
Merged
Changes from all 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
29 changes: 25 additions & 4 deletions src/objectid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ import { type InspectFn, defaultInspect } from './parser/utils';
import { ByteUtils } from './utils/byte_utils';
import { NumberUtils } from './utils/number_utils';

// Regular expression that checks for hex value
const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');

// Unique sequence for the current process (initialized on first use)
let PROCESS_UNIQUE: Uint8Array | null = null;

Expand Down Expand Up @@ -112,7 +109,7 @@ export class ObjectId extends BSONValue {
// If intstanceof matches we can escape calling ensure buffer in Node.js environments
this.buffer = ByteUtils.toLocalBufferType(workingId);
} else if (typeof workingId === 'string') {
if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
if (ObjectId.validateHexString(workingId)) {
this.buffer = ByteUtils.fromHex(workingId);
} else {
throw new BSONError(
Expand Down Expand Up @@ -143,6 +140,29 @@ export class ObjectId extends BSONValue {
}
}

/**
* @internal
* Validates the input string is a valid hex representation of an ObjectId.
*/
private static validateHexString(string: string): boolean {
if (string?.length !== 24) return false;
for (let i = 0; i < 24; i++) {
const char = string.charCodeAt(i);
if (
// Check for ASCII 0-9
(char >= 48 && char <= 57) ||
// Check for ASCII a-f
(char >= 97 && char <= 102) ||
// Check for ASCII A-F
(char >= 65 && char <= 70)
) {
continue;
}
return false;
}
return true;
}

/** Returns the ObjectId id as a 24 lowercase character hex string representation */
toHexString(): string {
if (ObjectId.cacheHexString && this.__id) {
Expand Down Expand Up @@ -329,6 +349,7 @@ export class ObjectId extends BSONValue {
*/
static isValid(id: string | number | ObjectId | ObjectIdLike | Uint8Array): boolean {
if (id == null) return false;
if (typeof id === 'string') return ObjectId.validateHexString(id);

try {
new ObjectId(id);
Expand Down