new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Electron · Tutorial · all subjects

performance

39 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Offscreen rendering efficiency: dirty area only

Offscreen rendering in Electron is optimized so that only the dirty area is passed to the paint event, rather than the entire frame, making rendering more efficient.

Offscreen rendering stops when page is idle

When nothing is happening on a webpage, no frames are generated in offscreen rendering mode.

Offscreen rendering overview and purpose

Offscreen rendering lets you obtain the content of a BrowserWindow in a bitmap or a shared GPU texture, so it can be rendered anywhere, such as on a texture in a 3D scene. Electron's offscreen rendering uses a similar approach to the Chromium Embedded Framework project.

GPU accelerated offscreen rendering with shared texture

When webPreferences.offscreen.useSharedTexture is set to true, offscreen rendering uses GPU shared texture mode. This is an advanced feature requiring a native node module. Frames are directly copied to GPU textures, making this mode very fast because there is no CPU-GPU memory copy overhead. You can directly import the shared texture to your own rendering program.

GPU accelerated offscreen rendering with CPU bitmap

When webPreferences.offscreen.useSharedTexture is set to false (default behavior), GPU accelerated rendering uses CPU shared memory bitmap mode. The texture is accessible using the NativeImage API, but this comes at a performance cost because the frame must be copied from GPU to CPU bitmap, requiring more system resources. This mode is slower than software output device mode but supports GPU-related functionalities like WebGL and 3D CSS animations.

Software output device offscreen rendering

Software output device mode uses a software output device for rendering in the CPU, making frame generation faster than GPU accelerated shared memory bitmap mode. To enable this mode, GPU acceleration must be disabled by calling the app.disableHardwareAcceleration() API.

GPU accelerated rendering supports WebGL and 3D CSS

GPU accelerated rendering modes in offscreen rendering support WebGL and 3D CSS animations.

Example: basic offscreen rendering with paint event

This example demonstrates offscreen rendering by disabling hardware acceleration, creating a BrowserWindow with offscreen enabled, and capturing frames from the paint event to save as PNG files: ```javascript const { app, BrowserWindow } = require('electron/main') const fs = require('node:fs') const path = require('node:path') app.disableHardwareAcceleration() function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { offscreen: true } }) win.loadURL('https://github.com') win.webContents.on('paint', (event, dirty, image) => { fs.writeFileSync('ex.png', image.toPNG()) }) win.webContents.setFrameRate(60) console.log(`The screenshot has been successfully saved to ${path.join(process.cwd(), 'ex.png')}`) } app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) ```

Offscreen rendering frame rate control

You can stop and continue offscreen rendering as well as set the frame rate using setFrameRate().

Offscreen rendering maximum frame rate with CPU bitmap

When webPreferences.offscreen.useSharedTexture is false, the maximum frame rate is 240 because greater values bring only performance losses with no benefits.

Main process handles all system interactions

When the operating system tells the app about a mouse click, it goes through the main process before reaching the window. If a window renders a smooth animation, it needs to talk to the GPU process through the main process. Blocking the UI thread blocks these critical operations.

Use worker threads for CPU-heavy tasks

For long-running CPU-heavy tasks in the main process, use worker threads or move them to the BrowserWindow. As a last resort, spawn a dedicated process. This prevents blocking the main process and UI thread.

Avoid synchronous IPC

Avoid using synchronous IPC and the @electron/remote module as much as possible. While there are legitimate use cases, it is far too easy to unknowingly block the UI thread.

Use asynchronous I/O in main process

Avoid using blocking I/O operations in the main process. When core Node.js modules like fs or child_process offer both synchronous and asynchronous versions, prefer the asynchronous non-blocking variant.

Prevent stuttering with renderer process optimization

The renderer process executes JavaScript for the app UI. To keep the app smooth and responsive, execute operations as quickly as possible without taking away resources needed to keep scrolling smooth, respond to user input, or maintain 60fps animations. Orchestrating the flow of operations in the renderer's code is particularly useful if users complain about the app stuttering.

Use Web Workers for long-running operations

Web Workers are a powerful tool to run code on a separate thread without blocking the main thread. They are an ideal solution for operations requiring significant CPU power for an extended period of time. Consult Electron's multithreading documentation and MDN documentation for Web Workers before using them.

Avoid unnecessary polyfills

Electron's major benefit is knowing exactly which engine will parse JavaScript, HTML, and CSS. If re-purposing code written for the web, do not polyfill features already included in Electron. JavaScript-based polyfills are rarely faster than equivalent native features in Electron.

Check feature support in Electron's Chromium version

Before using polyfills or workarounds, check caniuse.com and verify whether the version of Chromium used in the target Electron version supports the desired feature. The Chromium version can be found in the process.versions.chrome property.

Remove unnecessary libraries

Carefully examine libraries used in the application. Many popular libraries like jQuery have had their most useful features integrated into standard JavaScript. Verify that libraries are truly necessary before shipping them.

Target latest ECMAScript in transpiler configuration

If using a transpiler/compiler like TypeScript, examine its configuration and ensure that it is targeting the latest ECMAScript version supported by Electron. This reduces the need for polyfills and improves performance.

Bundle rarely-changing resources with app

Avoid fetching rarely-changing resources from the internet if they could easily be bundled with the application. This reduces network requests and improves app responsiveness. For example, Google Fonts should be downloaded and included in the app's bundle rather than fetched from a CDN.

Use Network tab to identify unnecessary requests

Open developer tools and navigate to the Network tab. Check the Disable cache option and reload the renderer. This shows all network requests being made. Focus on larger files first and identify resources that don't change and could be bundled with the app.

Use Network Throttling to identify blocking requests

In the Network tab developer tools, enable Network Throttling and select a slower speed like Fast 3G, then reload the renderer. This reveals resources that the app is unnecessarily waiting for despite not actually needing them.

Use Service Workers for dynamic resource loading

Loading resources from the internet that might need to change without shipping an app update is a powerful strategy. For advanced control over how resources are being loaded, consider using Service Workers.

Bundle application code into single file

Bundle the application's code into a single file to ensure the overhead of calling require() is only paid once when the application loads. Webpack, Parcel, and rollup.js are popular bundlers that handle Electron's unique environment needing both Node.js and browser support.

Recommended JavaScript bundlers for Electron

Popular bundler choices for Electron include Webpack, Parcel, and rollup.js. Choose a bundler able to handle Electron's unique environment that needs to handle both Node.js and browser environments.

Call Menu.setApplicationMenu(null) to improve startup

If building a custom menu or using a frameless window without native menu, call Menu.setApplicationMenu(null) before app.on('ready'). This prevents Electron from setting up a default menu, which benefits startup performance.

Default menu setup blocks startup performance

Electron will set a default menu on startup with standard entries. If the application does not need this default menu, it should be prevented to improve startup performance.

Use requestIdleCallback for small operations

requestIdleCallback() allows developers to queue a function to be executed as soon as the process enters an idle period. It enables low-priority or background work without impacting user experience.

Profiling is the most reliable performance strategy

The most successful strategy for building a performant Electron app is to profile the running code, find the most resource-hungry piece of it, and optimize it. Repeating this process over and over again will dramatically increase performance. Major apps like Visual Studio Code and Slack have shown that this practice is by far the most reliable strategy to improve performance.

Use Chrome Developer Tools for performance profiling

Chrome Developer Tools can be used to profile an Electron app's code. The Chrome Tracing tool is recommended for advanced analysis looking at multiple processes at once.

Profile module loading costs with node command

Module loading costs can be analyzed using the command 'node --cpu-prof --heap-prof -e "require('module-name')"'. This generates a .cpuprofile file and a .heapprofile file in the current directory, which can be analyzed using Chrome Developer Tools Performance and Memory tabs respectively.

Avoid carelessly including large Node.js modules

When adding a Node.js module to an Electron application, examine the module's dependencies and the resources required to load it. A module popular on NPM may not be the leanest option. Modules written for Node.js servers may perform poorly in Electron apps because they may load, parse, and store in memory information that is not actually needed.

Check module dependencies before use

When considering a module, check: 1) the size of dependencies included, 2) the resources required to load it, 3) the resources required to perform the desired action.

Defer expensive setup operations

If expensive setup operations are required, consider deferring them. Instead of firing off all operations when the application starts, stagger them in a sequence more closely aligned with the user's journey.

Defer module loading to when needed

Loading modules is an expensive operation, especially on Windows. Modules that are not immediately needed should be loaded later when they are actually required. Use lazy loading where require() statements are placed inside functions or methods called later rather than at the top level.

Allocate resources just-in-time

Resources should be allocated when they are needed rather than when the application starts. This reduces startup time and improves initial responsiveness.

Never block the main process

The Electron main process (browser process) is special: it is the parent process to all other processes and houses the UI thread. It handles windows, interactions, communication between components, and interacts with the operating system. Blocking this process and the UI thread with long-running operations will freeze the entire app until the main process finishes.

WebView performance and control tradeoff

Compared to an iframe, webview tends to be slightly slower but offers much greater control in loading and communicating with third-party content and handling various events.

Give your agent this brain