From c7fc64642a263a02bf701060ade61e5ca584d279 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Thu, 7 Feb 2019 16:30:34 +0000 Subject: [PATCH] perf: cache buffer form of CID when created refs https://github.com/ipfs/js-ipfs/issues/1788 License: MIT Signed-off-by: Alan Shaw --- src/index.js | 20 ++++++++++++++------ test/index.spec.js | 11 +++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/index.js b/src/index.js index dc8aba1..41e6f64 100644 --- a/src/index.js +++ b/src/index.js @@ -122,18 +122,26 @@ class CID { * @memberOf CID */ get buffer () { - switch (this.version) { - case 0: - return this.multihash - case 1: - return Buffer.concat([ + let buffer = this._buffer + + if (!buffer) { + if (this.version === 0) { + buffer = this.multihash + } else if (this.version === 1) { + buffer = Buffer.concat([ Buffer.from('01', 'hex'), multicodec.getCodeVarint(this.codec), this.multihash ]) - default: + } else { throw new Error('unsupported version') + } + + // Cache this buffer so it doesn't have to be recreated + Object.defineProperty(this, '_buffer', { value: buffer }) } + + return buffer } /** diff --git a/test/index.spec.js b/test/index.spec.js index 7c318f7..19bd4e6 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -300,4 +300,15 @@ describe('CID', () => { }) }) }) + + describe('buffer reuse', () => { + it('should cache CID as buffer', done => { + multihashing(Buffer.from(`TEST${Date.now()}`), 'sha2-256', (err, hash) => { + if (err) return done(err) + const cid = new CID(1, 'dag-pb', hash) + expect(cid.buffer).to.equal(cid.buffer) + done() + }) + }) + }) })