Skip to content

Commit b1eae69

Browse files
committed
optimized most common objectId usage new ObjectId()
1 parent 35f5264 commit b1eae69

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

lib/bson/objectid.js

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10);
1010

1111
// Regular expression that checks for hex value
1212
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
13+
var hasBufferType = false;
14+
15+
// Check if buffer exists
16+
try {
17+
if(Buffer && Buffer.from) hasBufferType = true;
18+
} catch(err) {};
1319

1420
/**
1521
* Create a new ObjectID instance
@@ -26,17 +32,26 @@ var ObjectID = function ObjectID(id) {
2632

2733
this._bsontype = 'ObjectID';
2834

29-
var __id = null;
35+
// The most common usecase (blank id, new objectId instance)
36+
if(id == null || typeof id == 'number') {
37+
// Generate a new id
38+
this.id = this.generate(id);
39+
// If we are caching the hex string
40+
if(ObjectID.cacheHexString) this.__id = this.toString('hex');
41+
// Return the object
42+
return;
43+
}
44+
45+
// Check if the passed in id is valid
3046
var valid = ObjectID.isValid(id);
3147

3248
// Throw an error if it's not a valid setup
3349
if(!valid && id != null){
3450
throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
51+
} else if(valid && typeof id == 'string' && id.length == 24 && hasBufferType) {
52+
return new ObjectID(Buffer.from(id, 'hex'));
3553
} else if(valid && typeof id == 'string' && id.length == 24) {
3654
return ObjectID.createFromHexString(id);
37-
} else if(id == null || typeof id == 'number') {
38-
// convert to 12 byte binary string
39-
this.id = this.generate(id);
4055
} else if(id != null && id.length === 12) {
4156
// assume 12 byte string
4257
this.id = id;
@@ -47,7 +62,7 @@ var ObjectID = function ObjectID(id) {
4762
throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
4863
}
4964

50-
if(ObjectID.cacheHexString) this.__id = this.toHexString();
65+
if(ObjectID.cacheHexString) this.__id = this.toString('hex');
5166
};
5267

5368
// Allow usage of ObjectId as well as ObjectID
@@ -155,7 +170,7 @@ ObjectID.prototype.generate = function(time) {
155170
*/
156171
ObjectID.prototype.toString = function(format) {
157172
// Is the id a buffer then use the buffer toString method to return the format
158-
if(this.id instanceof Buffer) {
173+
if(this.id && this.id.copy) {
159174
return this.id.toString(format || 'hex');
160175
}
161176

0 commit comments

Comments
 (0)