diff --git a/packages/sdk/src/util/splay_tree.ts b/packages/sdk/src/util/splay_tree.ts index 30d64a038..5f9a6ce36 100644 --- a/packages/sdk/src/util/splay_tree.ts +++ b/packages/sdk/src/util/splay_tree.ts @@ -170,9 +170,13 @@ export abstract class SplayNode { */ export class SplayTree { private root?: SplayNode; + private static readonly SPLAY_THRESHOLD = 500; + private linearCount: number; + private firstNode?: SplayNode; constructor(root?: SplayNode) { this.root = root; + this.linearCount = 0; } /** @@ -211,7 +215,7 @@ export class SplayTree { `out of index range: pos: ${pos} > node.length: ${node.getLength()}`, ); } - this.splayNode(node) + this.splayNode(node); return [node, pos]; } @@ -226,7 +230,7 @@ export class SplayTree { return -1; } - this.splayNode(node) + this.splayNode(node); return this.root!.getLeftWeight(); } @@ -257,6 +261,18 @@ export class SplayTree { return newNode; } + if (target == this.root) { + this.linearCount++; + if (this.linearCount == 1) { + this.firstNode = newNode; + } else if (this.linearCount > SplayTree.SPLAY_THRESHOLD) { + this.splayNode(this.firstNode); + this.linearCount = 0; + } + } else { + this.linearCount = 0; + } + this.splayNode(target); this.root = newNode; newNode.setRight(target.getRight());