From c79dcf8c5c162168562d491c520bee585c1bdf01 Mon Sep 17 00:00:00 2001 From: Johannes Rieken Date: Wed, 12 Jan 2022 17:23:46 +0100 Subject: [PATCH] use "sliding window" average for language feature delays, https://github.com/microsoft/vscode/issues/140557 --- src/vs/base/common/numbers.ts | 34 +++++++++++++++++++ .../languages/languageFeatureRegistry.ts | 6 ++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/vs/base/common/numbers.ts b/src/vs/base/common/numbers.ts index 9edfddfe5338a..3b06c0d26b9e8 100644 --- a/src/vs/base/common/numbers.ts +++ b/src/vs/base/common/numbers.ts @@ -34,3 +34,37 @@ export class MovingAverage { return this._val; } } + +export class SlidingWindowAverage { + + private _n: number = 0; + private _val = 0; + + private readonly _values: number[] = []; + private _index: number = 0; + private _sum = 0; + + constructor(size: number) { + this._values = new Array(size); + this._values.fill(0, 0, size); + } + + update(value: number) { + const oldValue = this._values[this._index]; + this._values[this._index] = value; + this._index = (this._index + 1) % this._values.length; + + this._sum -= oldValue; + this._sum += value; + + if (this._n < this._values.length) { + this._n += 1; + } + + this._val = this._sum / this._n; + } + + get value(): number { + return this._val; + } +} diff --git a/src/vs/editor/common/languages/languageFeatureRegistry.ts b/src/vs/editor/common/languages/languageFeatureRegistry.ts index 80fde38e2aa42..e1de00b5e6e49 100644 --- a/src/vs/editor/common/languages/languageFeatureRegistry.ts +++ b/src/vs/editor/common/languages/languageFeatureRegistry.ts @@ -7,7 +7,7 @@ import { Emitter, Event } from 'vs/base/common/event'; import { doHash } from 'vs/base/common/hash'; import { IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { LRUCache } from 'vs/base/common/map'; -import { MovingAverage } from 'vs/base/common/numbers'; +import { SlidingWindowAverage } from 'vs/base/common/numbers'; import { ITextModel } from 'vs/editor/common/model'; import { LanguageFilter, LanguageSelector, score } from 'vs/editor/common/languages/languageSelector'; import { shouldSynchronizeModel } from 'vs/editor/common/services/model'; @@ -197,7 +197,7 @@ function weakHash(obj: object): number { */ export class LanguageFeatureRequestDelays { - private readonly _cache = new LRUCache(50, 0.7); + private readonly _cache = new LRUCache(50, 0.7); constructor( @@ -228,7 +228,7 @@ export class LanguageFeatureRequestDelays { const key = this._key(model); let avg = this._cache.get(key); if (!avg) { - avg = new MovingAverage(); + avg = new SlidingWindowAverage(12); this._cache.set(key, avg); } avg.update(value);