Performance and Optimization
8 min read
Course: Electron
Topic 9: Performance and Optimization 🚀
Building an Electron application is empowering. You get the flexibility of web technologies combined with the raw power of a desktop environment. However, with great power comes the very real possibility of building an app that consumes a user's entire RAM and takes ten seconds to open.
In the industry, users expect desktop apps to be snappy, lightweight, and responsive. In this guide, we are going to explore the core concepts of Electron performance optimization, focusing on what is actually used in production today.
1. Keeping the Main Process Lightweight and Non-Blocking
Definition:
The Main Process is the central control environment of an Electron application. It runs a Node.js instance and is responsible for creating application windows, interacting with native operating system APIs (like menus and dialogs), and managing the lifecycle of the app.
The Problem:
The Main Process runs on a single thread. If you execute a heavy, synchronous operation on this thread (like reading a massive file synchronously or performing a dense mathematical loop), the thread becomes blocked. When the Main Process is blocked, it cannot process any other events. The entire application—including all visual windows and UI interactions—will completely freeze until that operation finishes.
(Imagine you are running a pizza shop (the main process). You have customers (UI events) coming in constantly. If you, the chef, decide to leave the kitchen to personally harvest wheat for the dough (a heavy synchronous task) every time an order comes in, you are going to have a bad time. You need to stay in the kitchen to keep the line moving while someone else does the heavy lifting.)
The Solution:
Keep the Main Process strictly dedicated to orchestration. Defer heavy I/O operations by using asynchronous APIs.
Industry Standard Practice:
Never use *Sync methods from Node.js (like readFileSync) in the Main Process unless it is absolutely necessary during the initial boot sequence. Always use Promises or async/await.
// ❌ BAD: Blocking the Main Process
const fs = require('fs');
const { ipcMain } = require('electron');
ipcMain.on('read-huge-file', (event, filePath) => {
// The entire app freezes while this 2GB file is read
const data = fs.readFileSync(filePath, 'utf-8');
event.reply('file-data', data);
});// ✅ GOOD: Non-Blocking the Main Process
const fs = require('fs').promises;
const { ipcMain } = require('electron');
ipcMain.handle('read-huge-file', async (event, filePath) => {
try {
// The main process is free to handle other UI events while waiting
const data = await fs.readFile(filePath, 'utf-8');
return data;
} catch (error) {
console.error("Failed to read file:", error);
}
});2. Memory Management: Preventing Leaks in Windows
Definition:
A memory leak occurs when a computer program allocates memory for an object but fails to release it back to the system when the object is no longer needed.
The Problem:
In Electron, creating a BrowserWindow is heavily resource-intensive. Under the hood, it spins up an entire Chromium rendering process. If a user closes a window in your app, but your Main Process still holds a JavaScript reference to that window object in an array or a variable, the JavaScript Garbage Collector cannot free up that memory. Over time, your app will quietly hoard gigabytes of RAM, creating "zombie" windows that are invisible but still draining system resources.
The Solution:
Always dereference (nullify) window objects immediately when they are closed.
Industry Standard Practice:
When managing multiple windows, keep track of them using a Set or an Array, but make sure to aggressively remove the reference inside the window's closed event listener.
const { app, BrowserWindow } = require('electron');
// We store window references here so they aren't garbage collected PREMATURELY
let windows = new Set();
function createNewWindow() {
let win = new BrowserWindow({ width: 800, height: 600 });
windows.add(win);
win.loadURL('https://freecodecamp.org');
// ✅ GOOD: Listen for the 'closed' event to prevent memory leaks
win.on('closed', () => {
windows.delete(win); // Remove from our tracking set
win = null; // Dereference the object completely
});
}
app.whenReady().then(createNewWindow);By explicitly setting win = null and removing it from your global tracking structures, you signal to Node.js that it is safe to incinerate the data and give the RAM back to the user's computer.
3. Offloading Heavy Tasks: Hidden Windows vs Worker Threads
Definition:
Background processing is the act of running CPU-intensive operations out of the user's sight so that the visual interface remains smooth.
The Problem:
If you have a task that requires intense CPU calculation—like processing a video file, compressing images, or parsing a 500MB JSON file—you cannot run it in the Renderer process (it will freeze the UI) and you cannot run it in the Main Process (it will freeze the app).
Historically, developers solved this by creating "Hidden Windows" (a BrowserWindow created with show: false). They would send data to this invisible browser window to do the math. However, spinning up an entire hidden browser—complete with an HTML DOM, CSS parsers, and a Chromium renderer—just to do a math equation is like renting an entire baseball stadium just to play catch. It wastes an enormous amount of memory.
The Solution:
Modern Electron apps completely avoid hidden windows. Instead, we use Node.js Worker Threads (for pure JavaScript calculations) or Electron's utilityProcess (for tasks requiring isolation or heavy Node.js integrations).
- Worker Threads: Share the same memory space as the parent but run on different CPU cores. Best for pure math/data processing.
- Utility Process: A dedicated API in Electron that uses Chromium's Services API to spawn a completely separate, lightweight child process. It is the modern replacement for Node's
child_process.fork.
Industry Standard Practice (utilityProcess):
// main.js
const { app, utilityProcess } = require('electron');
const path = require('path');
app.whenReady().then(() => {
// ✅ GOOD: Spawning a lightweight utility process
const child = utilityProcess.fork(path.join(__dirname, 'heavy-task.js'));
// Listen for messages from the child process
child.on('message', (msg) => {
console.log('Result from background task:', msg);
});
// Send data to be processed
child.postMessage({ action: 'process-video', file: 'vacation.mp4' });
});// heavy-task.js (Runs completely independent of the Main/Renderer threads)
process.parentPort.on('message', (event) => {
const { action, file } = event.data;
if (action === 'process-video') {
// Perform heavy CPU blocking task here safely!
let result = performMassiveCalculation(file);
process.parentPort.postMessage(`Finished processing ${file}: ${result}`);
}
});
function performMassiveCalculation(file) {
// Simulating 5 seconds of CPU burning work
const start = Date.now();
while (Date.now() - start < 5000) {}
return "Success";
}4. Startup Time Optimization Strategies
Definition:
Startup time is the duration it takes from the exact moment a user clicks your application's icon to the moment the application is fully visible and interactive.
The Problem:
Because Electron bundles Node.js and Chromium, it inherently takes a bit of time to boot. However, developers often make it worse by throwing all their code at the initialization phase. When you use require() at the top of a file, Node.js must synchronously read that file from the hard drive, parse the JavaScript, and load it into memory. If you require massive libraries (like the AWS SDK or heavy database drivers) at the top of your main.js, your app will stare blankly at the user for 5 to 10 seconds before rendering a window.
The Solution:
Use Lazy Loading (also known as deferred loading). You should only load modules exactly when you need them, not a second earlier.
Industry Standard Practice:
Instead of putting all require() statements at the top of your file, move the heavy ones inside the functions that actually use them. Prioritize showing the BrowserWindow to the user as quickly as possible.
// ❌ BAD: Synchronously loading heavy modules on startup
const { app, BrowserWindow, ipcMain } = require('electron');
const aws = require('aws-sdk'); // Heavy!
const massiveDBDriver = require('pg'); // Heavy!
function createWindow() {
const win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL('https://freecodecamp.org');
}
app.whenReady().then(createWindow);// ✅ GOOD: Lazy Loading modules only when requested
const { app, BrowserWindow, ipcMain } = require('electron');
// 1. App boots instantly because we only required Electron
function createWindow() {
const win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL('https://freecodecamp.org');
}
app.whenReady().then(createWindow);
// 2. We only load the heavy database driver when the user actually triggers the event
ipcMain.handle('fetch-user-data', async () => {
const massiveDBDriver = require('pg'); // Lazy loaded!
const client = new massiveDBDriver.Client();
await client.connect();
// ... fetch data
});By lazy loading, the user gets visual feedback (the app window opening) almost immediately, which makes the application feel infinitely faster, even if background tasks are still initializing.
Summary Checklist for a Performant Electron App:
- Never block the Main Process: Treat it like a VIP traffic cop. Use Promises and async operations.
- Clean up your garbage: Nullify window references on the
closedevent. - Kill hidden windows: Offload intense mathematical or I/O work to Node
worker_threadsor Electron'sutilityProcess. - Lazy load your code: Don't
require()the kitchen sink before the UI even renders.
📚 References & Extra Reading
Challenge
You have been tasked with optimizing a core main.js file from an Electron application that is exhibiting poor performance and memory leaks. Your goal is to refactor the existing code to implement several critical performance improvements without altering the application's core logic.
Your Tasks:
- Fix Main Process Blocking: The
loadAppConfigfunction currently reads a configuration file synchronously, blocking the main process on startup. Modify it to perform this operation asynchronously. - Resolve Memory Leak: The application is leaking memory because it does not properly dereference the
BrowserWindowinstance after it is closed. Correct the'closed'event listener to ensure the garbage collector can reclaim the memory. - Implement Lazy Loading: A large analytics module is currently loaded at startup, slowing down the initial launch time. Refactor the code to load this module only when it is first required by the
send-analyticsIPC handler. - Offload Heavy Computation: The
process-large-fileIPC handler simulates a long-running, blocking task directly on the main process, which would freeze the entire application's UI. Modify this handler to delegate the work to a separateutilityProcess. You should fork a new process pointing to a conceptual script located atpath.join(__dirname, 'worker.js'). You do not need to write the worker script itself, only the logic to spawn it.
Expected result
Your refactored code should meet the following criteria:
- The
loadAppConfigfunction is declared asasyncand now usesawait fs.promises.readFile()to load the configuration file without blocking. - The
createWindowfunction is updated to correctlyawaitthe new asynchronousloadAppConfigfunction. - Inside the
mainWindow.on('closed', ...)callback, themainWindowvariable is set tonull. - The line
const analytics = require('heavy-analytics-sdk');is removed from the top of the file. - The
require('heavy-analytics-sdk')call is now placed inside theipcMain.handle('send-analytics', ...)handler function. - The
ipcMain.handle('process-large-file', ...)handler is cleared of the synchronous blocking loop and now contains a call toutilityProcess.fork(path.join(__dirname, 'worker.js'))to delegate the task.