From 539490becd7653b0c02d46a4634a05bec34d1521 Mon Sep 17 00:00:00 2001 From: m4ushold Date: Wed, 2 Oct 2024 14:21:38 +0900 Subject: [PATCH 1/2] optimize splay tree To prevent the tree from becoming skewed, I balanced it by splaying the first node of the sequence every 500 linear insert operations. The value 500 was determined experimentally. --- packages/sdk/src/util/splay_tree.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/sdk/src/util/splay_tree.ts b/packages/sdk/src/util/splay_tree.ts index 30d64a038..585d701b0 100644 --- a/packages/sdk/src/util/splay_tree.ts +++ b/packages/sdk/src/util/splay_tree.ts @@ -170,9 +170,12 @@ export abstract class SplayNode { */ export class SplayTree { private root?: SplayNode; + private linearCount : number; + private firstNode? : SplayNode; constructor(root?: SplayNode) { this.root = root; + this.linearCount = 0; } /** @@ -257,6 +260,18 @@ export class SplayTree { return newNode; } + if (target == this.root) { + this.linearCount++; + if (this.linearCount==1) { + this.firstNode = newNode; + } else if (this.linearCount > 500) { + this.splayNode(this.firstNode); + this.linearCount = 0; + } + } else { + this.linearCount = 0; + } + this.splayNode(target); this.root = newNode; newNode.setRight(target.getRight()); From 0329ccd7045210d41b9f5c4462efae46122b5aa9 Mon Sep 17 00:00:00 2001 From: m4ushold Date: Wed, 2 Oct 2024 19:48:41 +0900 Subject: [PATCH 2/2] Refactor code based on CodeRabbit AI recommendations Move hardcoded constant to readonly attribute in Splay Tree --- packages/sdk/src/util/splay_tree.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/sdk/src/util/splay_tree.ts b/packages/sdk/src/util/splay_tree.ts index 585d701b0..5f9a6ce36 100644 --- a/packages/sdk/src/util/splay_tree.ts +++ b/packages/sdk/src/util/splay_tree.ts @@ -170,8 +170,9 @@ export abstract class SplayNode { */ export class SplayTree { private root?: SplayNode; - private linearCount : number; - private firstNode? : SplayNode; + private static readonly SPLAY_THRESHOLD = 500; + private linearCount: number; + private firstNode?: SplayNode; constructor(root?: SplayNode) { this.root = root; @@ -214,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]; } @@ -229,7 +230,7 @@ export class SplayTree { return -1; } - this.splayNode(node) + this.splayNode(node); return this.root!.getLeftWeight(); } @@ -262,9 +263,9 @@ export class SplayTree { if (target == this.root) { this.linearCount++; - if (this.linearCount==1) { + if (this.linearCount == 1) { this.firstNode = newNode; - } else if (this.linearCount > 500) { + } else if (this.linearCount > SplayTree.SPLAY_THRESHOLD) { this.splayNode(this.firstNode); this.linearCount = 0; }