Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

refactor(core): drop base-performance tracing module (#7078)

白熱d26e5f1b003e
diff --git a/packages/core/src/base/base-performance.ts b/packages/core/src/base/base-performance.ts
deleted file mode 100644
index a5cb0f14da..0000000000
--- a/packages/core/src/base/base-performance.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-export type BasePerformanceDetails = Record<string, unknown>;
-
-interface IBasePerformanceGlobal {
- __UNIVER_BASE_PERF__?: boolean;
-}
-
-let measurementIndex = 0;
-
-export function isBasePerformanceTracingEnabled(): boolean {
- const globalObject = globalThis as typeof globalThis & IBasePerformanceGlobal;
- if (globalObject.__UNIVER_BASE_PERF__ === true) {
- return true;
- }
-
- try {
- const locationSearch = typeof location === 'undefined' ? '' : location.search;
- const searchParams = new URLSearchParams(locationSearch);
- if (searchParams.get('basePerf') === '1' || searchParams.get('basePerf') === 'true' || searchParams.get('base-perf') === '1') {
- return true;
- }
- } catch {
- // Ignore URL parsing failures in non-browser runtimes.
- }
-
- try {
- const value = typeof localStorage === 'undefined' ? null : localStorage.getItem('univer.basePerf');
- return value === '1' || value === 'true';
- } catch {
- return false;
- }
-}
-
-export function traceBasePerformance<T>(label: string, fn: () => T, details?: BasePerformanceDetails): T {
- if (!isBasePerformanceTracingEnabled()) {
- return fn();
- }
-
- const start = now();
- const markId = `base-core-perf-${measurementIndex++}`;
- mark(`${markId}:start`);
- try {
- return fn();
- } finally {
- const duration = now() - start;
- mark(`${markId}:end`);
- measure(label, `${markId}:start`, `${markId}:end`);
- logBasePerformance(label, duration, details);
- }
-}
-
-export function logBasePerformance(label: string, duration: number, details?: BasePerformanceDetails): void {
- if (!isBasePerformanceTracingEnabled()) {
- return;
- }
-
- const roundedDuration = Math.round(duration * 100) / 100;
- const payload = details && Object.keys(details).length
- ? ` ${JSON.stringify(details)}`
- : '';
- // eslint-disable-next-line no-console
- console.info(`[BasePerf] ${label}: ${roundedDuration}ms${payload}`);
-}
-
-function now(): number {
- return typeof performance !== 'undefined' && typeof performance.now === 'function'
- ? performance.now()
- : Date.now();
-}
-
-function mark(name: string): void {
- try {
- if (typeof performance !== 'undefined') {
- performance.mark?.(name);
- }
- } catch {
- // Ignore unsupported performance APIs.
- }
-}
-
-function measure(name: string, start: string, end: string): void {
- try {
- if (typeof performance !== 'undefined') {
- performance.measure?.(`[BasePerf] ${name}`, start, end);
- }
- } catch {
- // Ignore unsupported performance APIs.
- }
-}
diff --git a/packages/core/src/base/__tests__/base-data-model.spec.ts b/packages/core/src/bases/__tests__/base-data-model.spec.ts
similarity index 100%
rename from packages/core/src/base/__tests__/base-data-model.spec.ts
rename to packages/core/src/bases/__tests__/base-data-model.spec.ts
diff --git a/packages/core/src/base/base-data-model.ts b/packages/core/src/bases/base-data-model.ts
similarity index 84%
rename from packages/core/src/base/base-data-model.ts
rename to packages/core/src/bases/base-data-model.ts
index 336eacfd0f..e65c73960e 100644
--- a/packages/core/src/base/base-data-model.ts
+++ b/packages/core/src/bases/base-data-model.ts
@@ -20,7 +20,6 @@ import { BehaviorSubject } from 'rxjs';
import { UnitModel, UniverInstanceType } from '../common/unit';
import { Tools } from '../shared/tools';
import { CellValueType } from '../types/enum';
-import { isBasePerformanceTracingEnabled, traceBasePerformance } from './base-performance';
const BASE_LIST_VALUE_SEPARATOR = ', ';
const BASE_ATTACHMENT_RESOURCE_KEY_SEPARATOR = '\u001F';
@@ -37,7 +36,7 @@ export class BaseDataModel extends UnitModel<IBaseSnapshot, UniverInstanceType.U
super();
const now = Date.now();
- this._snapshot = traceBasePerformance('Core.BaseDataModel.normalizeSnapshot', () => normalizeBaseSnapshot(Tools.commonExtend({
+ this._snapshot = normalizeBaseSnapshot(Tools.commonExtend({
id: '',
name: '',
schemaVersion: 1,
@@ -46,9 +45,7 @@ export class BaseDataModel extends UnitModel<IBaseSnapshot, UniverInstanceType.U
createdAt: now,
updatedAt: now,
rev: 1,
- } as IBaseSnapshot, snapshot)), {
- tables: Object.keys(snapshot.tables ?? {}).length,
- });
+ } as IBaseSnapshot, snapshot));
if (!this._snapshot.id) {
this._snapshot.id = `base-${Math.random().toString(36).slice(2, 10)}`;
@@ -99,57 +96,25 @@ function normalizeBaseSnapshot(snapshot: IBaseSnapshot): IBaseSnapshot {
delete (snapshot as IBaseSnapshot & { compress?: unknown }).compress;
delete (snapshot as IBaseSnapshot & { kind?: unknown }).kind;
Object.values(snapshot.tables ?? {}).forEach((table) => {
- if (!isBasePerformanceTracingEnabled()) {
- normalizeBaseTable(table);
- return;
- }
-
- traceBasePerformance('Core.BaseDataModel.normalizeTable', () => normalizeBaseTable(table), {
- tableId: table.id,
- records: Object.keys(table.records ?? {}).length,
- fields: table.fieldOrder.length,
- });
+ normalizeBaseTable(table);
});
return snapshot;
}
function normalizeBaseTable(table: ITableSnapshot): void {
- traceBasePerformance('Core.BaseDataModel.hydrateCompressedCellData', () => hydrateCompressedCellData(table), {
- tableId: table.id,
- });
+ hydrateCompressedCellData(table);
const records = table.records ?? {};
const fields = table.fields ?? {};
- const orderedRecordIds = traceBasePerformance('Core.BaseDataModel.getOrderedRecordIds', () => getOrderedRecordIds(table, records), {
- tableId: table.id,
- records: Object.keys(records).length,
- hasRecordOrder: Boolean(table.recordOrder?.length),
- });
- const orderedFieldIds = traceBasePerformance('Core.BaseDataModel.getOrderedFieldIds', () => getOrderedFieldIds(table, fields), {
- tableId: table.id,
- fields: Object.keys(fields).length,
- });
+ const orderedRecordIds = getOrderedRecordIds(table, records);
+ const orderedFieldIds = getOrderedFieldIds(table, fields);
table.recordOrder = orderedRecordIds;
- traceBasePerformance('Core.BaseDataModel.cloneMutableMaps', () => cloneBaseTableMutableMaps(table), {
- tableId: table.id,
- });
- traceBasePerformance('Core.BaseDataModel.normalizeExistingCellData', () => normalizeExistingCellData(table, fields), {
- tableId: table.id,
- });
- traceBasePerformance('Core.BaseDataModel.rebuildRowIndexes', () => rebuildRowIndexes(table, records, orderedRecordIds), {
- tableId: table.id,
- records: orderedRecordIds.length,
- });
- traceBasePerformance('Core.BaseDataModel.rebuildColumnIndexes', () => rebuildColumnIndexes(table, fields, orderedFieldIds), {
- tableId: table.id,
- fields: orderedFieldIds.length,
- });
- traceBasePerformance('Core.BaseDataModel.hydrateRecordCellData', () => hydrateRecordCellData(table, records, fields), {
- tableId: table.id,
- records: orderedRecordIds.length,
- fields: orderedFieldIds.length,
- });
+ cloneBaseTableMutableMaps(table);
+ normalizeExistingCellData(table, fields);
+ rebuildRowIndexes(table, records, orderedRecordIds);
+ rebuildColumnIndexes(table, fields, orderedFieldIds);
+ hydrateRecordCellData(table, records, fields);
}
function hydrateCompressedCellData(table: ITableSnapshot): void {
diff --git a/packages/core/src/base/index.ts b/packages/core/src/bases/index.ts
similarity index 100%
rename from packages/core/src/base/index.ts
rename to packages/core/src/bases/index.ts
diff --git a/packages/core/src/base/typedef.ts b/packages/core/src/bases/typedef.ts
similarity index 100%
rename from packages/core/src/base/typedef.ts
rename to packages/core/src/bases/typedef.ts
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f15e9d7959..0d272d3fe0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -18,7 +18,7 @@ import { installShims } from './common/shims';
installShims();
-export * from './base';
+export * from './bases';
export { dedupe, dedupeBy, groupBy, makeArray, remove, rotate } from './common/array';
export * from './common/async';
export { isBooleanString } from './common/boolean';
diff --git a/packages/core/src/services/instance/instance.service.ts b/packages/core/src/services/instance/instance.service.ts
index cc12a64380..e2829124d5 100644
--- a/packages/core/src/services/instance/instance.service.ts
+++ b/packages/core/src/services/instance/instance.service.ts
@@ -19,7 +19,6 @@ import type { IDisposable } from '../../common/di';
import type { UnitModel } from '../../common/unit';
import type { Nullable } from '../../shared';
import { BehaviorSubject, distinctUntilChanged, filter, map, Subject } from 'rxjs';
-import { traceBasePerformance } from '../../base/base-performance';
import { createIdentifier, Inject, Injector } from '../../common/di';
import { UniverInstanceType } from '../../common/unit';
import { DocumentDataModel } from '../../docs/data-model/document-data-model';
@@ -141,9 +140,7 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
}
createUnit<T, U extends UnitModel>(type: UniverInstanceType, data: T, options?: ICreateUnitOptions): U {
- const model = traceBasePerformance('Core.InstanceService.createUnitHandler', () => this._createHandler(type, data, this._ctorByType.get(type)!, options), {
- type,
- });
+ const model = this._createHandler(type, data, this._ctorByType.get(type)!, options);
return model as U;
}
@@ -195,36 +192,25 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
* @param unit The unit to be added.
*/
__addUnit(unit: UnitModel, options?: ICreateUnitOptions): void {
- traceBasePerformance('Core.InstanceService.__addUnit', () => {
- this._logService.debug(`[UniverInstanceService]: Adding unit with id ${unit.getUnitId()}`);
- const type = unit.type;
+ this._logService.debug(`[UniverInstanceService]: Adding unit with id ${unit.getUnitId()}`);
+ const type = unit.type;
- if (!this._unitsByType.has(type)) {
- this._unitsByType.set(type, []);
- }
+ if (!this._unitsByType.has(type)) {
+ this._unitsByType.set(type, []);
+ }
- const units = this._unitsByType.get(type)!;
- const newUnitId = unit.getUnitId();
- if (units.findIndex((u) => u.getUnitId() === newUnitId) !== -1) {
- throw new Error(`[UniverInstanceService]: cannot create a unit with the same unit id: ${newUnitId}.`);
- }
+ const units = this._unitsByType.get(type)!;
+ const newUnitId = unit.getUnitId();
+ if (units.findIndex((u) => u.getUnitId() === newUnitId) !== -1) {
+ throw new Error(`[UniverInstanceService]: cannot create a unit with the same unit id: ${newUnitId}.`);
+ }
- units.push(unit);
- traceBasePerformance('Core.InstanceService.unitAdded.next', () => this._unitAdded$.next({ unit, options }), {
- type,
- unitId: unit.getUnitId(),
- });
-
- if (options?.makeCurrent ?? true) {
- traceBasePerformance('Core.InstanceService.setCurrentUnitForType', () => this.setCurrentUnitForType(unit.getUnitId()), {
- type,
- unitId: unit.getUnitId(),
- });
- }
- }, {
- type: unit.type,
- unitId: unit.getUnitId(),
- });
+ units.push(unit);
+ this._unitAdded$.next({ unit, options });
+
+ if (options?.makeCurrent ?? true) {
+ this.setCurrentUnitForType(unit.getUnitId());
+ }
}
private _unitDisposed$ = new Subject<UnitModel>();
diff --git a/packages/core/src/univer.ts b/packages/core/src/univer.ts
index 24686bffa2..497704430d 100644
--- a/packages/core/src/univer.ts
+++ b/packages/core/src/univer.ts
@@ -22,7 +22,6 @@ import type { DependencyOverride } from './services/plugin/plugin-override';
import type { Plugin, PluginCtor } from './services/plugin/plugin.service';
import type { ILocales } from './shared';
import type { LocaleType } from './types/enum/locale-type';
-import { traceBasePerformance } from './base/base-performance';
import { Injector, touchDependencies } from './common/di';
import { UniverInstanceType } from './common/unit';
import { DocumentDataModel } from './docs/data-model/document-data-model';
@@ -168,9 +167,7 @@ export class Univer implements IDisposable {
}
createUnit<T, U extends UnitModel>(type: UniverInstanceType, data: Partial<T>): U {
- return traceBasePerformance('Core.Univer.createUnit', () => this._univerInstanceService.createUnit(type, data), {
- type,
- });
+ return this._univerInstanceService.createUnit(type, data);
}
private _init(injector: Injector): void {
@@ -183,9 +180,7 @@ export class Univer implements IDisposable {
(type: UniverInstanceType, data, ctor, options) => {
const isFirstTime = !this._startedTypes.has(type);
if (isFirstTime) {
- traceBasePerformance('Core.Univer.startPluginsForType', () => this._pluginService.startPluginsForType(type), {
- type,
- });
+ this._pluginService.startPluginsForType(type);
this._startedTypes.add(type);
}
@@ -194,19 +189,11 @@ export class Univer implements IDisposable {
throw new Error(`[Univer]: No constructor registered for unit type ${type}.`);
}
- const model = traceBasePerformance('Core.Univer.createModelInstance', () => injector.createInstance(actualCtor, data), {
- type,
- ctor: actualCtor.name,
- });
- traceBasePerformance('Core.Univer.addUnit', () => univerInstanceService.__addUnit(model, options), {
- type,
- unitId: model.getUnitId(),
- });
+ const model = injector.createInstance(actualCtor, data);
+ univerInstanceService.__addUnit(model, options);
if (isFirstTime) {
- traceBasePerformance('Core.Univer.tryProgressToReady', () => this._tryProgressToReady(), {
- type,
- });
+ this._tryProgressToReady();
}
return model;