CIDv1.buffer recomputes the byte representation on every access by calling multicodec.add_prefix() and concatenating bytes. Go stores the bytes once in the Cid struct. For CIDs accessed frequently (e.g., in sets, dicts, or comparisons), this causes unnecessary overhead.
Problem
In cid/cid.py:
class CIDv1(BaseCID):
@property
def buffer(self) -> bytes:
return b"".join([
bytes([self.version]),
multicodec.add_prefix(self.codec, self.multihash)
])
# ← Recomputed every time .buffer is accessed
This is called by:
encode() — every time the CID is serialized
to_bytes() — alias for buffer
key_string() — calls buffer
__hash__() — via BaseCID, uses multihash not buffer (OK)
prefix() — calls mh.decode(self.multihash) (separate issue)
Proposed Solution
Cache the buffer on first computation:
class CIDv1(BaseCID):
def __init__(self, codec, multihash):
super().__init__(1, codec, multihash)
self._buffer = None
@property
def buffer(self) -> bytes:
if self._buffer is None:
self._buffer = b"".join([
bytes([self.version]),
multicodec.add_prefix(self.codec, self.multihash)
])
return self._buffer
Related
CIDv1.bufferrecomputes the byte representation on every access by callingmulticodec.add_prefix()and concatenating bytes. Go stores the bytes once in theCidstruct. For CIDs accessed frequently (e.g., in sets, dicts, or comparisons), this causes unnecessary overhead.Problem
In
cid/cid.py:This is called by:
encode()— every time the CID is serializedto_bytes()— alias for bufferkey_string()— calls buffer__hash__()— via BaseCID, uses multihash not buffer (OK)prefix()— callsmh.decode(self.multihash)(separate issue)Proposed Solution
Cache the buffer on first computation:
Related
cid/cid.py