From 83edf3650e768f70922cb3dd9d08a67693577660 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Fri, 14 Dec 2018 09:34:21 +0100 Subject: [PATCH] perf: memoize the Name buffer in DAGLink to avoid unneeded allocations Allocating two buffers for every comparison was quite expensive. This commit replaces Buffer.compare with String.prototype.localeCompare. Fixes: https://github.com/ipld/js-ipld-dag-pb/issues/107 Fixes: https://github.com/ipld/js-ipld-dag-pb/issues/104 --- src/dag-link/index.js | 13 +++++++++++++ src/dag-node/util.js | 5 +---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/dag-link/index.js b/src/dag-link/index.js index 521b9e6..64d14a9 100644 --- a/src/dag-link/index.js +++ b/src/dag-link/index.js @@ -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) } @@ -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") } diff --git a/src/dag-node/util.js b/src/dag-node/util.js index 2086fbf..e4e01e6 100644 --- a/src/dag-node/util.js +++ b/src/dag-node/util.js @@ -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) } /*