Skip to content

Commit adeb03c

Browse files
author
Mike Dirolf
committed
precompute machine + pid bytes for ObjectId generation
1 parent 45b9b78 commit adeb03c

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

pymongo/objectid.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,28 @@
3030
from errors import InvalidId
3131

3232

33+
def _machine_and_pid_bytes():
34+
"""Get the machine and pid portion of an ObjectId.
35+
"""
36+
# 3 bytes machine
37+
machine_hash = _md5func()
38+
machine_hash.update(socket.gethostname())
39+
bytes = machine_hash.digest()[0:3]
40+
41+
# 2 bytes pid
42+
bytes += struct.pack(">H", os.getpid() % 0xFFFF)
43+
return bytes
44+
45+
3346
class ObjectId(object):
3447
"""A Mongo ObjectId.
3548
"""
3649

3750
_inc = 0
3851
_inc_lock = threading.Lock()
3952

53+
_machine_and_pid_bytes = _machine_and_pid_bytes()
54+
4055
def __init__(self, id=None):
4156
"""Initialize a new ObjectId.
4257
@@ -62,13 +77,8 @@ def __generate(self):
6277
# 4 bytes current time
6378
oid += struct.pack(">i", int(time.time()))
6479

65-
# 3 bytes machine
66-
machine_hash = _md5func()
67-
machine_hash.update(socket.gethostname())
68-
oid += machine_hash.digest()[0:3]
69-
70-
# 2 bytes pid
71-
oid += struct.pack(">H", os.getpid() % 0xFFFF)
80+
# 3 bytes machine + 2 bytes pid
81+
oid += ObjectId._machine_and_pid_bytes
7282

7383
# 3 bytes inc
7484
ObjectId._inc_lock.acquire()

0 commit comments

Comments
 (0)