massive performance degradation
More by accident I stumbled over a massive performance degradation during high input load.
Repro:
- generate big blob of terminal data with at least some SGR (34 MB on my computer)
ls -lR --color=always /usr > term_data
- register two OSC handler for time measuring in console of demo:
term.parser.registerOscHandler(3333, data => { window._pp = {wall: Date.now(), perf: performance.now()}; });
term.parser.registerOscHandler(2222, data => { console.log(Date.now() - window._pp.wall, performance.now() - window._pp.perf); });
- run the following in xterm.js shell 3 times with devtools being closed:
echo -e '\x1b]3333\x1b' && cat term_data && echo -e '\x1b]2222\x1b'
- inspect values in console
Observations
- Bufferline._copySparseMapsFrom & Bufferline._invalidateStringCache are very expensive (see #6101)
- DecorationLineCache._handleBufferLinesTrim is very expensive with high GC loads (crashes firefox in profiling) (see #6120)
- very high setTimeout/clearTimeout pressure from WriteBuffer & SmoothScrollableElement._scheduleHide (see #6102)
Quickfix to see impact of recent changes (diff is below)
- comment out
this._copySparseMapsFrom(line);in Bufferline.copyFrom - comment out Bufferline._invalidateStringCache
- comment out DecorationLineCache._handleBufferLinesTrim
- replace TimeoutTimer.cancelAndSet in WriteBuffer & SmoothScrollableElement._scheduleHide with less toxic versions
Results:
- Chrome: ~3000ms, after quickfix ~2000ms
- Firefox: ~15000ms, after quickfix ~4200ms
Firefox profiler gives a nice flamegraph to better spot where the cycles are spent. But I was not able to do that for main (profiler and firefox tab kept crashing), here the one with the quickfix applied: https://share.firefox.dev/45WSYn4 (open with firefox, should open a profiler page). It shows, that almost 30% is spent in Viewport.ts, the scrollbar handling being very expensive. 50% is spent in Inputhandler.print, maybe another ground to have a closer look again.
Diff of quickfix:
diff --git a/src/browser/scrollable/scrollableElement.ts b/src/browser/scrollable/scrollableElement.ts
index df3628e10..3c2da6736 100644
--- a/src/browser/scrollable/scrollableElement.ts
+++ b/src/browser/scrollable/scrollableElement.ts
@@ -11,7 +11,7 @@ import { HorizontalScrollbar } from './horizontalScrollbar';
import { IScrollableElementChangeOptions, IScrollableElementCreationOptions, IScrollableElementResolvedOptions } from './scrollableElementOptions';
import { VerticalScrollbar } from './verticalScrollbar';
import { Widget } from './widget';
-import { TimeoutTimer } from '../../common/Async';
+import { queueDebouncedMacrotask, TimeoutTimer } from '../../common/Async';
import { Emitter, IEvent } from '../../common/Event';
import { IDisposable, dispose } from '../../common/Lifecycle';
import * as platform from '../../common/Platform';
@@ -535,7 +535,8 @@ export class SmoothScrollableElement extends Widget {
private _scheduleHide(): void {
if (!this._mouseIsOver && !this._isDragging) {
- this._hideTimeout.cancelAndSet(() => this._hide(), Constants.HIDE_TIMEOUT);
+ //this._hideTimeout.cancelAndSet(() => this._hide(), Constants.HIDE_TIMEOUT);
+ queueDebouncedMacrotask('hide-scroll', () => this._hide(), Constants.HIDE_TIMEOUT);
}
}
}
diff --git a/src/common/Async.ts b/src/common/Async.ts
index 3189d6293..4c656f33d 100644
--- a/src/common/Async.ts
+++ b/src/common/Async.ts
@@ -139,3 +139,118 @@ export class IntervalTimer implements IDisposable {
this._isDisposed = true;
}
}
+
+
+
+
+class MacrotaskScheduler {
+ static instance: MacrotaskScheduler | null = null;
+ private _pool!: {p1: MessagePort; p2: MessagePort}[];
+ private _poolIndex!: number;
+ private _debounceTimestamps!: Map<string, number>;
+ private _debounceActive!: Set<string>;
+
+ constructor(initialSize = 16) {
+ if (MacrotaskScheduler.instance) {
+ return MacrotaskScheduler.instance;
+ }
+ this._pool = [];
+ this._poolIndex = 0;
+ this._resizePool(initialSize);
+ this._debounceTimestamps = new Map();
+ this._debounceActive = new Set();
+ MacrotaskScheduler.instance = this;
+ }
+
+ private _resizePool(targetSize: number) {
+ const toAdd = targetSize - this._pool.length;
+ for (let i = 0; i < toAdd; i++) {
+ const ch = new MessageChannel();
+ this._pool.push({ p1: ch.port1, p2: ch.port2 });
+ }
+ }
+
+ public queue(callback: Function, delay = 0, signal?: AbortSignal) {
+ if (signal && signal.aborted) return;
+
+ if (delay > 0) {
+ const timeoutId = setTimeout(() => {
+ if (signal) signal.removeEventListener("abort", cancelTimeout);
+ callback();
+ }, delay);
+
+ const cancelTimeout = () => clearTimeout(timeoutId);
+ if (signal) signal.addEventListener("abort", cancelTimeout);
+ return;
+ }
+
+ if (this._poolIndex >= this._pool.length) {
+ this._resizePool(this._pool.length * 2);
+ }
+
+ const slot = this._pool[this._poolIndex++];
+
+ const cleanup = () => {
+ slot.p1.onmessage = null;
+ if (signal) signal.removeEventListener("abort", onAbort);
+ this._poolIndex--;
+ };
+
+ const onAbort = () => cleanup();
+
+ slot.p1.onmessage = () => {
+ cleanup();
+ callback();
+ };
+
+ if (signal) signal.addEventListener("abort", onAbort);
+ slot.p2.postMessage(null);
+ }
+
+ public queueDebounced(key: string, callback: Function, delay: number, signal?: AbortSignal) {
+ if (signal && signal.aborted) return;
+
+ const now = performance.now();
+ this._debounceTimestamps.set(key, now);
+ if (this._debounceActive.has(key)) return;
+ this._debounceActive.add(key);
+
+ const checkWindow = () => {
+ if (signal && signal.aborted) {
+ this._cleanupDebounce(key);
+ return;
+ }
+
+ const lastActivity = this._debounceTimestamps.get(key) || 0;
+ const timePassed = performance.now() - lastActivity;
+
+ if (timePassed >= delay) {
+ this._cleanupDebounce(key);
+ callback();
+ } else {
+ const remainingTime = delay - timePassed;
+ setTimeout(checkWindow, remainingTime);
+ }
+ };
+
+ setTimeout(checkWindow, delay);
+ }
+
+ private _cleanupDebounce(key: string) {
+ this._debounceTimestamps.delete(key);
+ this._debounceActive.delete(key);
+ }
+}
+
+const schedulerInstance = new MacrotaskScheduler(16);
+
+
+
+export function queueMacrotask(callback: Function, delay = 0, signal?: AbortSignal) {
+ schedulerInstance.queue(callback, delay, signal);
+}
+
+
+export function queueDebouncedMacrotask(key: string, callback: Function, delay = 0, signal?: AbortSignal) {
+ schedulerInstance.queueDebounced(key, callback, delay, signal);
+}
diff --git a/src/common/buffer/BufferLine.ts b/src/common/buffer/BufferLine.ts
index 30b4ed3bb..5d8aa7f73 100644
--- a/src/common/buffer/BufferLine.ts
+++ b/src/common/buffer/BufferLine.ts
@@ -467,7 +467,9 @@ export class BufferLine implements IBufferLine {
this._data.set(line._data);
}
this.length = line.length;
- this._copySparseMapsFrom(line);
+ //this._copySparseMapsFrom(line);
+ this._combined = {};
+ this._extendedAttrs = {};
this.isWrapped = line.isWrapped;
}
@@ -597,11 +599,11 @@ export class BufferLine implements IBufferLine {
}
private _invalidateStringCache(): void {
- const cacheEntry = this._getStringCacheEntry(false);
- if (cacheEntry) {
- cacheEntry.value = undefined;
- cacheEntry.isTrimmed = false;
- }
+ //const cacheEntry = this._getStringCacheEntry(false);
+ //if (cacheEntry) {
+ // cacheEntry.value = undefined;
+ // cacheEntry.isTrimmed = false;
+ //}
}
/** Copy sparse map entries for a single cell when `_data` flags require them. */
diff --git a/src/common/input/WriteBuffer.ts b/src/common/input/WriteBuffer.ts
index 0b4619690..a1d2e1ab3 100644
--- a/src/common/input/WriteBuffer.ts
+++ b/src/common/input/WriteBuffer.ts
@@ -4,7 +4,7 @@
* @license MIT
*/
-import { TimeoutTimer } from '../Async';
+import { queueMacrotask, TimeoutTimer } from '../Async';
import { Disposable, toDisposable } from '../Lifecycle';
import { Emitter } from '../Event';
@@ -213,7 +213,8 @@ export class WriteBuffer extends Disposable {
if (this._store.isDisposed) {
return;
}
- this._innerWriteTimer.cancelAndSet(() => this._innerWrite(lastTime, promiseResult), 0);
+ //this._innerWriteTimer.cancelAndSet(() => this._innerWrite(lastTime, promiseResult), 0);
+ queueMacrotask(() => this._innerWrite(lastTime, promiseResult));
}
protected _innerWrite(lastTime: number = 0, promiseResult: boolean = true): void {
diff --git a/src/common/services/DecorationService.ts b/src/common/services/DecorationService.ts
index ea9b7fb14..b74140be9 100644
--- a/src/common/services/DecorationService.ts
+++ b/src/common/services/DecorationService.ts
@@ -214,26 +214,26 @@ export class DecorationLineCache extends Disposable {
}
private _handleBufferLinesTrim(amount: number): void {
- if (amount <= 0) {
- return;
- }
- const newMap = new Map<number, IInternalDecoration[]>();
- for (const [line, bucket] of this._decorationsByLine) {
- const newLine = line - amount;
- if (newLine < 0) {
- continue;
- }
- this._mergeLineBucket(newMap, newLine, bucket);
- }
- this._decorationsByLine.clear();
- for (const [line, bucket] of newMap) {
- this._decorationsByLine.set(line, bucket);
- }
- for (const d of this._decorations) {
- if (!d.marker.isDisposed) {
- d._indexedStartLine -= amount;
- }
- }
+ //if (amount <= 0) {
+ // return;
+ //}
+ //const newMap = new Map<number, IInternalDecoration[]>();
+ //for (const [line, bucket] of this._decorationsByLine) {
+ // const newLine = line - amount;
+ // if (newLine < 0) {
+ // continue;
+ // }
+ // this._mergeLineBucket(newMap, newLine, bucket);
+ //}
+ //this._decorationsByLine.clear();
+ //for (const [line, bucket] of newMap) {
+ // this._decorationsByLine.set(line, bucket);
+ //}
+ //for (const d of this._decorations) {
+ // if (!d.marker.isDisposed) {
+ // d._indexedStartLine -= amount;
+ // }
+ //}
}
private _handleBufferLinesInsert(event: IInsertEvent): void {
Opened #6110 for the TimeoutTimer.cancelAndSet/WriteBuffer piece of this (part of #6102).
Scope is deliberately narrow — swaps WriteBuffer._innerWriteTimer from TimeoutTimer (clearTimeout/setTimeout pair on every zero-delay reschedule, subject to the browser's ~4ms nested-timeout clamp) to a new MacrotaskTimer that posts through MessageChannel instead for the zero-delay case, falling back to setTimeout otherwise. SmoothScrollableElement._scheduleHide is a separate, lower-frequency debounce and isn't touched.
Did not attempt the Bufferline._copySparseMapsFrom / _invalidateStringCache or DecorationLineCache._handleBufferLinesTrim pieces — your quickfix diff comments those out for profiling, but a real fix needs the sparse-map copy and decoration-offset-on-trim behavior preserved (removing them silently drops extended attrs/combined chars on line copy and desyncs decoration positions on scrollback trim), so that's real algorithmic work rather than a scheduling swap. Leaving those, and the Viewport/InputHandler.print breakdown, to you or a follow-up.
The changes from #6114 & #6122 change the perf numbers as follows:
- Chrome went from 2.9s to 2.2s
- Firefox went from 17s to 11s
The remaining fixes are the TimoutTimer invocations in WriteBuffer and SmoothScrollableElement. The latter seems to be the reason, why firefox is so vastly off (see #6123).
Forecast: With the MacrotaskScheduler from above chrome ends up at 1.8s and firefox at 2.6s.
The new PR #6160 is one approach to eliminating the issues noted here.