Skip to content

Commit 6149fae

Browse files
achingbrainrvagg
authored andcommitted
fix!: remove use of Object.defineProperties in CID class
`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
1 parent 429bb27 commit 6149fae

File tree

2 files changed

+9
-16
lines changed

2 files changed

+9
-16
lines changed

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,8 @@
157157
"eslintConfig": {
158158
"extends": "ipfs",
159159
"parserOptions": {
160-
"sourceType": "module"
160+
"sourceType": "module",
161+
"ecmaVersion": 13
161162
}
162163
},
163164
"release": {

src/cid.js

+7-15
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ const baseCache = cid => {
6161
*/
6262

6363
export class CID {
64+
/** @type {CID} */
65+
#asCID
66+
6467
/**
6568
* @param {Version} version - Version of the CID
6669
* @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
@@ -86,20 +89,11 @@ export class CID {
8689

8790
// Circular reference
8891
/** @readonly */
89-
this.asCID = this
90-
91-
// Configure private properties
92-
Object.defineProperties(this, {
93-
byteOffset: hidden,
94-
byteLength: hidden,
95-
96-
code: readonly,
97-
version: readonly,
98-
multihash: readonly,
99-
bytes: readonly,
92+
this.#asCID = this
93+
}
10094

101-
asCID: hidden
102-
})
95+
get asCID () {
96+
return this.#asCID
10397
}
10498

10599
/**
@@ -568,5 +562,3 @@ const encodeCID = (version, code, multihash) => {
568562
}
569563

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

0 commit comments

Comments
 (0)