From 10f3d34dbda04b2f11463dfec8977da2136bd418 Mon Sep 17 00:00:00 2001 From: Hannah Redler Date: Thu, 21 Nov 2024 16:32:15 +0100 Subject: [PATCH] perf(imt): when updating a node, skip calculation if value is the same In order to improve performance, we can avoid recalculating the Incremental Merkel Tree in the event that the update value is the same as the tree value. re #340 --- packages/imt/src/imt.ts | 2 ++ packages/imt/tests/imt.test.ts | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/packages/imt/src/imt.ts b/packages/imt/src/imt.ts index 3774c1dfd..60f410976 100644 --- a/packages/imt/src/imt.ts +++ b/packages/imt/src/imt.ts @@ -224,6 +224,8 @@ export default class IMT { throw new Error("The leaf does not exist in this tree") } + if (newLeaf === this._nodes[0][index]) return + let node = newLeaf for (let level = 0; level < this.depth; level += 1) { diff --git a/packages/imt/tests/imt.test.ts b/packages/imt/tests/imt.test.ts index da179d1d0..ae7884a04 100644 --- a/packages/imt/tests/imt.test.ts +++ b/packages/imt/tests/imt.test.ts @@ -131,6 +131,25 @@ describe("IMT", () => { expect(tree.root).toEqual(root) } }) + + it(`Should not error when update value is the same`, () => { + for (let i = 0; i < numberOfLeaves; i += 1) { + tree.insert(1) + oldTree.insert(1) + } + + const previousRoot = tree.root + + for (let i = 0; i < numberOfLeaves; i += 1) { + tree.update(i, 1) + oldTree.update(i, 1) + + const { root } = oldTree.genMerklePath(0) + + expect(tree.root).toEqual(root) + expect(tree.root).toEqual(previousRoot) + } + }) }) describe("# indexOf", () => {