Skip to content

CIDv1.buffer property recomputes on every access #70

Description

@sumanjeet0012

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

  • File: cid/cid.py

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions