Skip to content

Commit

Permalink
fix!: remove use of Object.defineProperties in CID class
Browse files Browse the repository at this point in the history
`Object.defineProperties` is a performance bottleneck in applications that
create lots and lots of CIDs (e.g. IPFS) so this PR removes it.

The `asCID` property is changed to be a [private class field](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields)
which requires increasing the minimum supported EcmaScript version but I don't
know if that's a big deal or not.  It does seem to make the property non-enumerable
though.

The CID class now implements a `Link` interface that has public `byteOffset`
and `byteLength` properties so these become regular properties

`code`, `version`, `multihash` and `bytes` become writable/configurable
but they are marked with `@readonly` so maybe that's enough?

Fixes #200
  • Loading branch information
achingbrain authored and rvagg committed Oct 12, 2022
1 parent 429bb27 commit 6149fae
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 16 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@
"eslintConfig": {
"extends": "ipfs",
"parserOptions": {
"sourceType": "module"
"sourceType": "module",
"ecmaVersion": 13
}
},
"release": {
Expand Down
22 changes: 7 additions & 15 deletions src/cid.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ const baseCache = cid => {
*/

export class CID {
/** @type {CID} */
#asCID

/**
* @param {Version} version - Version of the CID
* @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
Expand All @@ -86,20 +89,11 @@ export class CID {

// Circular reference
/** @readonly */
this.asCID = this

// Configure private properties
Object.defineProperties(this, {
byteOffset: hidden,
byteLength: hidden,

code: readonly,
version: readonly,
multihash: readonly,
bytes: readonly,
this.#asCID = this
}

asCID: hidden
})
get asCID () {
return this.#asCID
}

/**
Expand Down Expand Up @@ -568,5 +562,3 @@ const encodeCID = (version, code, multihash) => {
}

const cidSymbol = Symbol.for('@ipld/js-cid/CID')
const readonly = { writable: false, configurable: false, enumerable: true }
const hidden = { writable: false, enumerable: false, configurable: false }

0 comments on commit 6149fae

Please sign in to comment.