From 6149fae84b74b7a6b0ca8f9e21e731ac9fabcf3a Mon Sep 17 00:00:00 2001 From: achingbrain Date: Thu, 22 Sep 2022 18:14:20 +0100 Subject: [PATCH] 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 --- package.json | 3 ++- src/cid.js | 22 +++++++--------------- 2 files changed, 9 insertions(+), 16 deletions(-) diff --git a/package.json b/package.json index 6e30571a..3099be32 100644 --- a/package.json +++ b/package.json @@ -157,7 +157,8 @@ "eslintConfig": { "extends": "ipfs", "parserOptions": { - "sourceType": "module" + "sourceType": "module", + "ecmaVersion": 13 } }, "release": { diff --git a/src/cid.js b/src/cid.js index cbb5fd80..ee563f52 100644 --- a/src/cid.js +++ b/src/cid.js @@ -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 @@ -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 } /** @@ -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 }