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

Commit

Permalink
perf: memoize the Name buffer in DAGLink to avoid unneeded allocations
Browse files Browse the repository at this point in the history
Allocating two buffers for every comparison was quite expensive.
This commit replaces Buffer.compare with String.prototype.localeCompare.

Fixes: #107
Fixes: #104
  • Loading branch information
mcollina authored and vmx committed Dec 17, 2018
1 parent 1eee975 commit 83edf36
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
13 changes: 13 additions & 0 deletions src/dag-link/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class DAGLink {
// for now to maintain consistency with go-ipfs pinset

this._name = name || ''
this._nameBuf = null
this._size = size
this._cid = new CID(cid)
}
Expand All @@ -37,6 +38,18 @@ class DAGLink {
return this._name
}

// Memoize the Buffer representation of name
// We need this to sort the links, otherwise
// we will reallocate new buffers every time
get nameAsBuffer () {
if (this._nameBuf !== null) {
return this._nameBuf
}

this._nameBuf = Buffer.from(this._name)
return this._nameBuf
}

set name (name) {
throw new Error("Can't set property: 'name' is immutable")
}
Expand Down
5 changes: 1 addition & 4 deletions src/dag-node/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ function cloneLinks (dagNode) {
}

function linkSort (a, b) {
const aBuf = Buffer.from(a.name || '')
const bBuf = Buffer.from(b.name || '')

return aBuf.compare(bBuf)
return Buffer.compare(a.nameAsBuffer, b.nameAsBuffer)
}

/*
Expand Down

0 comments on commit 83edf36

Please sign in to comment.