Skip to content
This repository was archived by the owner on Sep 3, 2021. It is now read-only.

Commit 37ede16

Browse files
author
Alan Shaw
committed
perf: cache buffer form of CID when created
refs ipfs/js-ipfs#1788 License: MIT Signed-off-by: Alan Shaw <[email protected]>
1 parent 2250475 commit 37ede16

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

src/index.js

+14-6
Original file line numberDiff line numberDiff line change
@@ -122,18 +122,26 @@ class CID {
122122
* @memberOf CID
123123
*/
124124
get buffer () {
125-
switch (this.version) {
126-
case 0:
127-
return this.multihash
128-
case 1:
129-
return Buffer.concat([
125+
let buffer = this._buffer
126+
127+
if (!buffer) {
128+
if (this.version === 0) {
129+
buffer = this.multihash
130+
} else if (this.version === 1) {
131+
buffer = Buffer.concat([
130132
Buffer.from('01', 'hex'),
131133
multicodec.getCodeVarint(this.codec),
132134
this.multihash
133135
])
134-
default:
136+
} else {
135137
throw new Error('unsupported version')
138+
}
139+
140+
// Cache this buffer so it doesn't have to be recreated
141+
Object.defineProperty(this, '_buffer', { value: buffer })
136142
}
143+
144+
return buffer
137145
}
138146

139147
/**

test/index.spec.js

+11
Original file line numberDiff line numberDiff line change
@@ -300,4 +300,15 @@ describe('CID', () => {
300300
})
301301
})
302302
})
303+
304+
describe('buffer reuse', () => {
305+
it('should cache CID as buffer', done => {
306+
multihashing(Buffer.from(`TEST${Date.now()}`), 'sha2-256', (err, hash) => {
307+
if (err) return done(err)
308+
const cid = new CID(1, 'dag-pb', hash)
309+
expect(cid.buffer).to.equal(cid.buffer)
310+
done()
311+
})
312+
})
313+
})
303314
})

0 commit comments

Comments
 (0)