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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(formular): fix dependency performance issue (#3359)
VicKunf2f7f5bb5035
diff --git a/packages/engine-formula/src/engine/dependency/dependency-tree.ts b/packages/engine-formula/src/engine/dependency/dependency-tree.tsindex 805e3d0b57..aacae7d041 100644--- a/packages/engine-formula/src/engine/dependency/dependency-tree.ts+++ b/packages/engine-formula/src/engine/dependency/dependency-tree.ts@@ -71,6 +71,11 @@ export class FormulaDependencyTree extends Disposable {isPassive: boolean = true;+ _childIds: Set<string> = new Set();++ // the left top cell , which means the position of the FormulaDependencyTree+ anchorToken: string = '';+getDirtyData: Nullable<(dirtyData: IFormulaDirtyData, runtimeData: IAllRuntimeData) => {runtimeCellData: IRuntimeUnitDataType;@@ -80,6 +85,16 @@ export class FormulaDependencyTree extends Disposable {private _state = FDtreeStateType.DEFAULT;+ private _id: string;+ constructor() {+ super();+ this._id = `${Math.random().toString(36).slice(3)}-${Math.random().toString(36).slice(3)}`;+ }++ get id() {+ return this._id;+ }+override dispose(): void {super.dispose();@@ -219,6 +234,11 @@ export class FormulaDependencyTree extends Disposable {pushChildren(tree: FormulaDependencyTree) {this.children.push(tree);tree._pushParent(this);+ this._childIds.add(tree.id);+ }++ hasChild(tree: FormulaDependencyTree) {+ return this._childIds.has(tree.id);}/**@@ -264,10 +284,16 @@ export class FormulaDependencyTree extends Disposable {interface IFormulaDependencyTreeCacheItem {unitRangeWithToken: IUnitRangeWithToken;treeList: FormulaDependencyTree[];+ ids: Set<string>;}export class FormulaDependencyTreeCache extends Disposable {private _cacheItems = new Map<string, IFormulaDependencyTreeCacheItem>();+ private _map = new Map<string, Map<string, Set<string>>>();+ private _dependencyMap = new Map<string, FormulaDependencyTree>();+ private _parentIdMap = new Map<string, string[]>();+ // use for mark the first cell of the range+ private _rangeTokens = new Set<string>();override dispose(): void {this.clear();@@ -277,6 +303,14 @@ export class FormulaDependencyTreeCache extends Disposable {return this._cacheItems.size;}+ getDependencyMap() {+ return this._dependencyMap;+ }++ getDependencyTree(id: string) {+ return this._dependencyMap.get(id);+ }+get length() {return this._cacheItems.size;}@@ -287,16 +321,56 @@ export class FormulaDependencyTreeCache extends Disposable {this._cacheItems.set(token, {unitRangeWithToken,treeList: [tree],+ ids: new Set<string>([tree.id]),});return;}const cacheItem = this._cacheItems.get(token)!;cacheItem.treeList.push(tree);+ cacheItem.ids.add(tree.id);++ const { gridRange } = unitRangeWithToken;++ const { range } = gridRange;+ if (!(range.startRow === range.endRow && range.startColumn === range.endColumn)) {+ this._rangeTokens.add(token);+ }+ }++ addDependencyMap(tree: FormulaDependencyTree) {+ this._dependencyMap.set(tree.id, tree);+ }++ updateParent(tree: FormulaDependencyTree) {+ const ids = new Set<string>();+ const unitId = tree.unitId;+ const sheetId = tree.subUnitId;+ const testCacheItems = this._cacheItems.get(tree.anchorToken);++ if (testCacheItems) {+ this._parentIdMap.set(tree.id, [...testCacheItems.ids]);+ return;+ }+ for (const token of this._rangeTokens) {+ const cacheItem = this._cacheItems.get(token);+ if (cacheItem) {+ const { unitRangeWithToken, treeList } = cacheItem;+ const { gridRange } = unitRangeWithToken;+ if (gridRange.unitId === unitId && gridRange.sheetId === sheetId && tree.inRangeData(gridRange.range)) {+ for (const tree of treeList) {+ ids.add(tree.id);+ }+ }+ }+ }+ this._parentIdMap.set(tree.id, [...ids]);}clear() {this._cacheItems.clear();+ this._map.clear();+ this._dependencyMap.clear();}remove(token: string, tree: FormulaDependencyTree) {@@ -315,6 +389,52 @@ export class FormulaDependencyTreeCache extends Disposable {this._cacheItems.delete(token);}+ getDependencyId(dependenceTree: FormulaDependencyTree, ids: Set<string>) {+ const parentIdList = this._parentIdMap.get(dependenceTree.id);+ if (parentIdList) {+ for (const parentId of parentIdList) {+ ids.add(parentId);+ const tree = this._dependencyMap.get(parentId);+ if (tree) {+ this.getDependencyId(tree, ids);+ }+ }+ }+ }++ /**+ * Determine whether range is dependent on other trees.+ * @param dependenceTree+ */++ dependencyUseParentId(dependenceTree: FormulaDependencyTree) {+ let ids = new Set<string>();++ this.getDependencyId(dependenceTree, ids);+ for (const parentId of ids) {+ const tree = this._dependencyMap.get(parentId);+ if (tree) {+ const notExist = tree.hasChild(dependenceTree);+ if (notExist && tree.rangeList) {+ for (const rangeItem of tree.rangeList) {+ if (rangeItem.gridRange.unitId === dependenceTree.unitId && rangeItem.gridRange.sheetId === dependenceTree.subUnitId) {+ tree.pushChildren(dependenceTree);+ break;+ }+ }+ }+ }++ if (tree && !tree.hasChild(dependenceTree)) {+ tree.pushChildren(dependenceTree);+ }+ }+ ids.clear();++ // @ts-ignore+ ids = null;+ }+/*** Determine whether range is dependent on other trees.* @param dependenceTreediff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.tsindex c50392e3fe..9202515ea1 100644--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts@@ -344,6 +344,18 @@ export class FormulaDependencyGenerator extends Disposable {FDtree.subUnitId = sheetId;FDtree.row = row;FDtree.column = column;+ const range = {+ range: {+ startRow: row,+ startColumn: column,+ endRow: row,+ endColumn: column,+ },+ unitId,+ sheetId,++ };+ FDtree.anchorToken = serializeRangeToRefString({ ...range, sheetName: this._currentConfigService.getSheetName(unitId, sheetId) });FDtree.rowCount = sheetItem.rowCount;FDtree.columnCount = sheetItem.columnCount;diff --git a/packages/engine-formula/src/engine/dependency/range-block-util.ts b/packages/engine-formula/src/engine/dependency/range-block-util.tsnew file mode 100644index 0000000000..c88f7bb990--- /dev/null+++ b/packages/engine-formula/src/engine/dependency/range-block-util.ts@@ -0,0 +1,91 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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.+ */++// import type { IRange } from '@univerjs/core';++// // the size of the block+// const BLOCKSIZE = 10;++// export function setRangeBlockToken(range: IRange, baseKey: string, token: string, map: Map<string, Map<string, Set<string>>>): void {+// const { startRow, startColumn, endRow, endColumn } = range;++// // 计算块的起始和结束索引+// const startH = Math.floor(startRow / BLOCKSIZE);+// const endH = Math.ceil(endRow / BLOCKSIZE);+// const startV = Math.floor(startColumn / BLOCKSIZE);+// const endV = Math.ceil(endColumn / BLOCKSIZE);++// // 遍历所有与range有交集的块+// for (let x = startH; x <= endH; x++) {+// for (let y = startV; y <= endV; y++) {+// const key = `${baseKey}_${x}_${y}`;+// if (!map.has(baseKey)) {+// map.set(baseKey, new Map());+// }+// if (!map.get(baseKey)!.has(key)) {+// map.get(baseKey)!.set(key, new Set<string>());+// }+// map.get(baseKey)!.get(key)!.add(token);+// }+// }+// }++// export function getBlockTokensByRange(tokensSet: Set<string>, range: IRange, baseKey: string, map: Map<string, Map<string, Set<string>>>): Set<string> {+// const { startRow, startColumn, endRow, endColumn } = range;++// // 计算块的起始和结束索引+// const startH = Math.floor(startRow / BLOCKSIZE);+// const endH = Math.floor(endRow / BLOCKSIZE);+// const startV = Math.floor(startColumn / BLOCKSIZE);+// const endV = Math.floor(endColumn / BLOCKSIZE);++// // 遍历所有与range有交集的块+// for (let x = startH; x <= endH; x++) {+// for (let y = startV; y <= endV; y++) {+// const key = `${baseKey}_${x}_${y}`;+// if (map.has(baseKey) && map.get(baseKey)!.has(key)) {+// const blockTokens = map.get(baseKey)!.get(key)!;+// blockTokens.forEach((token) => tokensSet.add(token));+// }+// }+// }++// return tokensSet;+// }++// export function updateBlockKey(tokensSet: Map<string, Set<string>>, range: IRange, baseKey: string, map: Map<string, Map<string, Set<string>>>) {+// const { startRow, startColumn, endRow, endColumn } = range;++// // 计算块的起始和结束索引+// const startH = Math.floor(startRow / BLOCKSIZE);+// const endH = Math.floor(endRow / BLOCKSIZE);+// const startV = Math.floor(startColumn / BLOCKSIZE);+// const endV = Math.floor(endColumn / BLOCKSIZE);++// let hasCreate = tokensSet.has(baseKey);++// // 遍历所有与range有交集的块+// for (let x = startH; x <= endH; x++) {+// for (let y = startV; y <= endV; y++) {+// if (!hasCreate) {+// tokensSet.set(baseKey, new Set<string>());+// hasCreate = true;+// }++// tokensSet.get(baseKey)?.add(`${baseKey}_${x}_${y}`);+// }+// }+// }diff --git a/packages/engine-formula/src/services/dependency-manager.service.ts b/packages/engine-formula/src/services/dependency-manager.service.tsindex 3caff5390c..e51e7e9a84 100644--- a/packages/engine-formula/src/services/dependency-manager.service.ts+++ b/packages/engine-formula/src/services/dependency-manager.service.ts@@ -138,60 +138,62 @@ export class DependencyManagerService extends Disposable implements IDependencyMbuildDependencyTree(shouldBeBuildTrees: FormulaDependencyTree[] | FormulaDependencyTreeCache, dependencyTrees?: FormulaDependencyTree[]): FormulaDependencyTree[] {const allTrees = this.getAllTree();- if (shouldBeBuildTrees.length === 0) {- this._buildReverseDependency(allTrees, dependencyTrees);- return allTrees;- }+ // if (shouldBeBuildTrees.length === 0) {+ // this._buildReverseDependency(allTrees, dependencyTrees);+ // return allTrees;+ // }if (shouldBeBuildTrees instanceof FormulaDependencyTreeCache) {- this._buildDependencyTree(allTrees, shouldBeBuildTrees, dependencyTrees || []);+ this._buildDependencyTreeWithCache(allTrees, shouldBeBuildTrees, dependencyTrees || []);} else {this._buildDependencyTree(allTrees, shouldBeBuildTrees, shouldBeBuildTrees);}-return allTrees;}+ private _buildDependencyTreeWithCache(allTrees: FormulaDependencyTree[], formulaDependencyTreeCache: FormulaDependencyTreeCache, dependencyTrees: FormulaDependencyTree[]) {+ const cache = new FormulaDependencyTreeCache();+ for (const tree of allTrees.concat(dependencyTrees)) {+ const rangeList = tree.rangeList;+ for (const range of rangeList) {+ cache.add(range, tree);+ cache.addDependencyMap(tree);+ }+ }++ const treeMap = cache.getDependencyMap();+ for (const tree of treeMap.values()) {+ cache.updateParent(tree);+ }+ for (const tree of treeMap.values()) {+ cache.dependencyUseParentId(tree);+ }+ cache.dispose();+ }+/*** Build the dependency relationship between the trees.* @param allTrees all FormulaDependencyTree* @param shouldBeBuildTrees FormulaDependencyTree[] | FormulaDependencyTreeCache*/- private _buildDependencyTree(allTrees: FormulaDependencyTree[], shouldBeBuildTrees: FormulaDependencyTree[] | FormulaDependencyTreeCache, dependencyTrees: FormulaDependencyTree[]) {- allTrees.forEach((tree) => {- if (shouldBeBuildTrees instanceof FormulaDependencyTreeCache) {- shouldBeBuildTrees.dependency(tree);- } else {- shouldBeBuildTrees.forEach((shouldBeBuildTree) => {- if (tree === shouldBeBuildTree || shouldBeBuildTree.children.includes(tree)) {- return true;- }-- if (shouldBeBuildTree.dependency(tree)) {- shouldBeBuildTree.pushChildren(tree);- }- });+ private _buildDependencyTree(allTrees: FormulaDependencyTree[], shouldBeBuildTrees: FormulaDependencyTree[], dependencyTrees: FormulaDependencyTree[]) {+ const cache = new FormulaDependencyTreeCache();+ for (const tree of allTrees.concat(shouldBeBuildTrees, dependencyTrees)) {+ const rangeList = tree.rangeList;+ for (const range of rangeList) {+ cache.add(range, tree);+ cache.addDependencyMap(tree);}- });- this._buildReverseDependency(allTrees, dependencyTrees);- }+ }+ // do not use allTrees.concat(shouldBeBuildTrees, dependencyTrees) to avoid duplicate trees+ const treeMap = cache.getDependencyMap();- /**- * Build the reverse dependency relationship between the trees.- * @param allTrees- * @param dependencyTrees- */- private _buildReverseDependency(allTrees: FormulaDependencyTree[], dependencyTrees?: FormulaDependencyTree[]) {- allTrees.forEach((tree) => {- dependencyTrees?.forEach((dependencyTree) => {- if (tree === dependencyTree || tree.children.includes(dependencyTree)) {- return true;- }-- if (tree.dependency(dependencyTree)) {- tree.pushChildren(dependencyTree);- }- });- });+ for (const tree of treeMap.values()) {+ cache.updateParent(tree);+ }+ for (const tree of treeMap.values()) {+ cache.dependencyUseParentId(tree);+ }+ cache.dispose();}/**