From e4ca34af8a520234ae4233e21337c4730b629a45 Mon Sep 17 00:00:00 2001 From: Chen Asraf Date: Fri, 9 Aug 2024 14:25:16 +0300 Subject: [PATCH] perf: improve init speed --- src/core/commands.ts | 13 +++++++++---- src/core/megahal.ts | 18 ++++++++++++++---- src/index.ts | 13 +++++++++---- 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/src/core/commands.ts b/src/core/commands.ts index 728266e..f06435e 100644 --- a/src/core/commands.ts +++ b/src/core/commands.ts @@ -28,12 +28,17 @@ export async function loadCommands(): Promise { _commands = {} const dir = path.resolve(__dirname, '..', 'commands') const files = await fs.readdir(dir) + const promises: Promise[] = [] for (const file of files) { - const command = (await import(path.resolve(dir, file))).default - logger.debug('Command loaded:', command.command) - _commands[command.command] = command + const promise = import(path.resolve(dir, file)).then((module) => { + const command = module.default + logger.debug('Command loaded:', command.command) + _commands[command.command] = command + return command + }) + promises.push(promise) } - return Object.values(_commands) + return Object.values(await Promise.all(promises)) } function cleanMessage(message: string): string { diff --git a/src/core/megahal.ts b/src/core/megahal.ts index 2733905..d38fbe3 100644 --- a/src/core/megahal.ts +++ b/src/core/megahal.ts @@ -29,15 +29,25 @@ let totalMsgCount = 0 export let chatterChance: number = DEFAULT_CHATTER_CHANCE logger.log('Initializing MegaHAL') -const start = Date.now() -export const megahal = new MegaHAL('venom') -const duration = Date.now() - start -logger.log('MegaHAL initialized in', duration, 'ms') +export let megahal: MegaHAL +let loaded = false loadBrain() +async function loadMegaHAL() { + const start = Date.now() + megahal ??= new MegaHAL('venom') + loaded = true + const duration = Date.now() - start + logger.log('MegaHAL initialized in', duration, 'ms') +} + async function loadBrain() { await reloadSettings() + if (!loaded) { + loadMegaHAL() + } + const exists = await fileExists(BRAIN_FILE) if (!exists) { diff --git a/src/index.ts b/src/index.ts index d30481e..5d6136a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,12 +13,17 @@ const client = new Client({ ], }) -loadCommands().then((commands) => - logger.log('Commands loaded:', commands.map((c) => c.command).join(', ')), -) +let start = Date.now() +logger.log('Loading commands...') +loadCommands().then((commands) => { + const duration = Date.now() - start + logger.log('Commands loaded:', commands.length + ',', 'took', duration, 'ms') +}) +start = Date.now() client.once(Events.ClientReady, (readyClient) => { - logger.log('Ready! Logged in as', readyClient.user.tag) + const duration = Date.now() - start + logger.log('Ready! Logged in as', readyClient.user.tag + ', ', 'took', duration, 'ms') readyClient.on(Events.MessageCreate, handleMessage) })