Skip to content

Commit

Permalink
perf(imt): when updating a node, skip calculation if value is the same (
Browse files Browse the repository at this point in the history
#350)

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
  • Loading branch information
hannahredler authored Nov 25, 2024
1 parent c126a7c commit c25353b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/imt/src/imt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
19 changes: 19 additions & 0 deletions packages/imt/tests/imt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down

0 comments on commit c25353b

Please sign in to comment.