From af7549a4988e89ed5c3977d235d078c8b2caa7a7 Mon Sep 17 00:00:00 2001 From: dudongcheng Date: Fri, 10 May 2024 15:43:06 +0800 Subject: [PATCH] refactor: optimize block creation with caching mechanism --- src/plugins/fast-input/BlockTypeInfo.js | 14 +++++++++++++- src/plugins/fast-input/WorkspaceQuerier.js | 10 +++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/plugins/fast-input/BlockTypeInfo.js b/src/plugins/fast-input/BlockTypeInfo.js index 4afa3ec..893f282 100644 --- a/src/plugins/fast-input/BlockTypeInfo.js +++ b/src/plugins/fast-input/BlockTypeInfo.js @@ -390,7 +390,7 @@ export class BlockTypeInfo { } for (const workspaceBlock of flyoutWorkspace.getTopBlocks()) { blocks.push( - ...BlockTypeInfo._createBlocks( + ...BlockTypeInfo._createBlocksWithCache( workspace, vm, Blockly, @@ -404,6 +404,18 @@ export class BlockTypeInfo { return blocks; } + static btiCache = {}; + + static _createBlocksWithCache(workspace, vm, Blockly, locale, workspaceForm, domForm) { + let blocks = BlockTypeInfo.btiCache[workspaceForm.id]; + if (blocks !== undefined) { + return blocks; + } + blocks = BlockTypeInfo._createBlocks(workspace, vm, Blockly, locale, workspaceForm, domForm); + BlockTypeInfo.btiCache[workspaceForm.id] = blocks; + return blocks; + } + static _createBlocks(workspace, vm, Blockly, locale, workspaceForm, domForm) { let parts = []; let inputs = []; diff --git a/src/plugins/fast-input/WorkspaceQuerier.js b/src/plugins/fast-input/WorkspaceQuerier.js index 65c9e28..ea68b1f 100644 --- a/src/plugins/fast-input/WorkspaceQuerier.js +++ b/src/plugins/fast-input/WorkspaceQuerier.js @@ -1229,6 +1229,10 @@ export default class WorkspaceQuerier { */ static MAX_TOKENS = 50000; + constructor() { + this._blockCache = {}; + } + /** * Indexes a workspace in preparation for querying it. * @param {BlockTypeInfo[]} blocks The list of blocks in the workspace. @@ -1435,7 +1439,11 @@ export default class WorkspaceQuerier { for (const block of blocks) { // console.log("block", typeof block, block); - const blockTokenType = new TokenTypeBlock(this, block); + let blockTokenType = this._blockCache[block.id]; + if (!blockTokenType) { + blockTokenType = new TokenTypeBlock(this, block); + this._blockCache[block.id] = blockTokenType; + } switch (block.shape) { case BlockShape.Round: this.tokenGroupRoundBlocks.pushProviders([blockTokenType]);