Files
ep-mail-client/electron-startup-optimization.md

5.6 KiB

Electron Startup Optimization: ep-mail-client

Current Problem

  • 15-20 seconds to see window
  • Root cause: 39 modules loaded synchronously before window creation
  • All services constructed at module load time (lines 121-220, 425-467 in main.cjs)

Quick Wins (Priority Order)

1. Enable V8 Bytecode Caching — 5 min, 30-50% gain

npm install v8-compile-cache-electron --save-dev

Add to top of desktop/main.cjs (before any other require):

require('v8-compile-cache-electron');

Caches compiled bytecode to disk — subsequent starts skip parsing/compilation.


2. Lazy-Load Heavy Modules — 30 min each, 500-1000ms gain each

Module Est. Load Time Where to Lazy-Load
openpgp ~500-1000ms Inside registerPgpIpcHandlers
imapflow ~300-500ms Inside createMailConnections
mailparser ~200-400ms Inside toUiMessage / createMailReader
tsdav + ical.js ~200-300ms Inside DAV handlers
nodemailer ~150-250ms Inside createMailConnections

Pattern:

// BEFORE (top-level)
const openpgp = require('openpgp');

// AFTER (lazy)
let openpgpPromise = null;
function getOpenPGP() {
  if (!openpgpPromise) openpgpPromise = import('openpgp');
  return openpgpPromise;
}
// Then: const openpgp = await getOpenPGP();

3. Defer Service Initialization Until After First Paint — 1 hr, shows window in 1-2s

Current: All services created at module load (before app.whenReady())

Fix: Move service creation into ready-to-show handler:

app.whenReady().then(() => {
  traceStartup('Electron app.whenReady');
  app.setAppUserModelId(windowsAppUserModelId);
  
  if (process.platform === 'win32') {
    windowsAppIcon = nativeImage.createFromPath(path.join(__dirname, '..', 'icon.ico'));
    if (windowsAppIcon.isEmpty()) throw new Error('Could not load the Windows application icon.');
  }

  // 1. Create window FIRST
  const mainWindow = createWindow();

  // 2. Defer heavy init until window is visible
  mainWindow.once('ready-to-show', () => {
    traceStartup('BrowserWindow ready-to-show');
    mainWindow.show();

    // NOW initialize heavy services (async, non-blocking)
    setImmediate(async () => {
      await initializeHeavyServices(); // move all createXxxService calls here
      if (process.platform === 'win32') {
        repairWindowsStartMenuShortcut();
        createWindowsTray();
      }
      void checkSnoozeReminders();
      setTimeout(() => requestBackgroundSync(), 3000);
      traceStartup('post-first-frame work started; background sync scheduled');
    });
  });

  // ... timers, etc.
});

4. Add Startup Profiling — 15 min, identifies real bottlenecks

Add to top of main.cjs:

const startupMarks = { mainStart: Date.now() };
function mark(label) {
  startupMarks[label] = Date.now();
  console.log(`[STARTUP] ${label}: +${startupMarks[label] - startupMarks.mainStart}ms`);
}

mark('beforeRequires');
// ... all your requires ...
mark('afterRequires');
// ... service creation ...
mark('afterServices');
// app.whenReady().then(() => {
mark('appReady');
// createWindow()
mark('windowCreated');
// ready-to-show
mark('readyToShow');

Run with:

EP_MAIL_STARTUP_TRACE=1 npm start

5. Build-Time Optimizations

In package.json build config:

"build": {
  "asar": true,
  "asarUnpack": [],
  "compression": "maximum"
}

Expected Results

Approach Startup Time
Current 15-20s
+ v8-compile-cache only ~8-12s
+ Lazy-load heavy deps ~4-7s
+ Defer service init (window shows early) Window visible in 1-2s, background init continues

Portable vs Installer Performance

The Problem

The portable .exe takes 12-15 seconds to show the window on every launch.

Root Cause

electron-builder's portable target creates a self-extracting 7z archive. On every launch:

  1. The .exe extracts the entire app to a temporary folder (%TEMP%/ep-mail-<random>/)
  2. Then runs the extracted ep-mail.exe
  3. This extraction happens every time, not just first run

Verified Performance by Build Type

Build Type Time to Window Notes
npm start (dev) ~476ms Development mode
NSIS Installer (recommended) ~422ms Installs to Program Files, runs natively
win-unpacked (dev/testing) ~422ms Direct execution, no extraction
Portable .exe 12-15s Self-extracts to %TEMP% on every launch

Recommendation

For distribution, use the NSIS installer (npm run dist:win:installer):

  • Installs permanently to Program Files
  • Runs at native speed (~422ms)
  • Creates Start Menu shortcuts
  • Supports auto-updates

The portable format is designed for USB stick usage where installation isn't possible. For daily use, the installer is the correct choice.


Implementation Checklist

  • Install v8-compile-cache-electron
  • Add require at top of main.cjs
  • Lazy-load openpgp (biggest single win)
  • Lazy-load imapflow, mailparser, nodemailer
  • Lazy-load tsdav, ical.js
  • Refactor main.cjs to defer service init until ready-to-show
  • Add profiling timestamps
  • Measure and verify

Files to Modify

  1. desktop/main.cjs — Primary target (all changes)
  2. package.json — Add devDependency, build config
  3. desktop/preload.cjs — Verify no unnecessary loads (currently clean ✅)

Generated: 2026-10-18