Skip to content

Instantly share code, notes, and snippets.

@sadn1ck
Created December 25, 2024 13:11
Show Gist options
  • Save sadn1ck/a673e34d3fd99588d6e0147c870f3d8c to your computer and use it in GitHub Desktop.
Save sadn1ck/a673e34d3fd99588d6e0147c870f3d8c to your computer and use it in GitHub Desktop.
yjs-ymap-bench
import * as prng from "lib0/prng";
import { v7 } from "uuid";
import { YKeyValue } from "y-utility/y-keyvalue";
import * as Y from "yjs";
// because i was also testing YKeyVal lol
abstract class BaseYDoc extends Y.Doc {
abstract yDoc: Y.Doc;
abstract baseMap: Y.Map<any> | YKeyValue<any>;
abstract widgetList: Y.Array<string>;
abstract gen: prng.PRNG;
createRandomWidgetInsideMap() {
const id = v7();
this.widgetList.push([id]);
const widget = new Y.Map();
widget.set("x", 0);
widget.set("y", 0);
widget.set("width", 100);
widget.set("height", 100);
widget.set("id", id);
this.baseMap.set(id, widget);
}
ensureNoWidgetHasStartingXY() {
for (const id of this.widgetList.toArray()) {
const widget = this.baseMap.get(id);
if (widget.get("x") === 0 && widget.get("y") === 0) {
return false;
}
}
return true;
}
moveWidget(id: string) {
const widget = this.baseMap.get(id);
const random = prng.uint32(this.gen, 0, 9999);
widget.set("x", random);
widget.set("y", random / 3);
}
benchmark() {
const numWidgets = 2000;
for (let i = 0; i < numWidgets; i++) {
this.createRandomWidgetInsideMap();
}
for (const id of this.widgetList.toArray()) {
for (let i = 0; i < numWidgets / 10; i++) {
this.moveWidget(id);
}
}
}
abstract runBenchmark(): void;
}
export class YDocWithMap extends BaseYDoc {
yDoc: Y.Doc;
baseMap: Y.Map<any>;
widgetList: Y.Array<string>;
gen = prng.create(5543);
constructor() {
super();
this.yDoc = new Y.Doc();
this.baseMap = this.yDoc.getMap("widgets");
this.widgetList = this.yDoc.getArray("widgetList");
}
runBenchmark() {
console.time("[YDocWithMap]");
this.benchmark();
console.timeEnd("[YDocWithMap]");
// compute size of yDoc
const v1ByteLength = Y.encodeStateAsUpdate(this.yDoc).byteLength;
const v2ByteLength = Y.encodeStateAsUpdateV2(this.yDoc).byteLength;
console.log(`[YDocWithMap] byteLength v1 ${v1ByteLength / 1024} KB`);
console.log(`[YDocWithMap] byteLength v2 ${v2ByteLength / 1024} KB`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment