Skip to content

Instantly share code, notes, and snippets.

@gerwld
Last active October 14, 2024 20:38
Show Gist options
  • Save gerwld/611ebdbc2844e89523b8d45fce175f4a to your computer and use it in GitHub Desktop.
Save gerwld/611ebdbc2844e89523b8d45fce175f4a to your computer and use it in GitHub Desktop.
General: JS

Several key techniques and best practices to help make JavaScript run extremely fast. Some of these involve optimizing how you handle objects, memory, and data structures, as well as leveraging modern JavaScript engine optimizations. Here are some key points:

1. Use Object.create(null) for Pure Maps/State Objects

  • When you create objects using {}, they inherit from Object.prototype, which can introduce unnecessary properties and methods. Using Object.create(null) creates an object with no prototype, making it a cleaner and faster option for objects used purely as maps or state stores. This reduces overhead from the prototype chain.

2. Avoid Creating Objects in Loops

  • Repeatedly creating objects inside a loop can lead to excessive memory allocations and garbage collection. Instead, reuse objects where possible or move object creation outside the loop.

3. Minimize the Use of Closures in Performance-Critical Code

  • While closures are powerful, they can sometimes lead to memory retention issues (holding references to outer scopes longer than necessary). In performance-critical sections, minimize the creation of unnecessary closures.

4. Prefer for Loops Over High-Level Iteration Functions

  • Iteration functions like forEach, map, filter, and reduce are convenient, but they add extra overhead compared to a simple for loop. When performance is critical (especially in hot paths), a traditional for loop can be faster.
for (let i = 0; i < array.length; i++) {
  // Fast!
}

5. Use TypedArray for Numeric Computations

  • If your code deals with large amounts of numeric data (e.g., arrays of numbers), consider using TypedArray objects like Int32Array, Float64Array, etc. Typed arrays are much more memory-efficient and can dramatically improve performance in certain use cases.
let typedArray = new Float32Array(1000);

6. Optimize Object Access Patterns

  • JavaScript engines like V8 optimize based on "hidden classes." If objects in your code follow consistent shapes (i.e., having the same properties in the same order), the engine can optimize access patterns. Avoid dynamically adding or removing properties from objects whenever possible.
  • Example: Avoid adding properties one by one:
    let obj = {};
    obj.a = 1;
    obj.b = 2; // Less optimized
    Instead, initialize the object with all properties at once:
    let obj = { a: 1, b: 2 }; // More optimized

7. Inline Functions in Critical Paths

  • Function calls have a performance overhead. Inlining small, frequently-called functions can reduce overhead. JavaScript engines may inline small functions automatically, but writing hot-path code with fewer function calls can sometimes yield performance benefits.

8. Avoid Deoptimizing Code

  • Certain actions can deoptimize your JavaScript code, forcing the engine to fall back to slower execution paths:
    • Mixing types in arrays ([1, 2, "three"]).
    • Using try/catch blocks excessively.
    • Using delete on object properties (this can destroy the object's "hidden class" optimization).

9. Use requestAnimationFrame for Animations

  • For smooth animations, avoid setTimeout or setInterval. Use requestAnimationFrame, which synchronizes with the browser's refresh rate and provides better performance and smoother visuals.
function animate() {
  // Your animation code
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

10. Lazy Load or Defer Non-Essential Code

  • Use lazy loading or deferring non-essential JavaScript until it's needed. This can reduce initial load times and improve the perceived performance of your app.

11. Avoid Memory Leaks

  • Be cautious of memory leaks, especially when dealing with event listeners, global variables, or circular references. Memory leaks lead to excessive memory usage and garbage collection, which can slow down your app over time.
  • Clean up event listeners when they're no longer needed:
    element.addEventListener('click', handleClick);
    // Later
    element.removeEventListener('click', handleClick);

12. Use Efficient Data Structures

  • Use more efficient data structures where applicable:
    • Arrays for ordered data.
    • Maps for key-value pairs (especially when the keys aren't strings).
    • Sets for unique values.
  • Maps and Sets offer faster lookup times than plain objects when used appropriately.

13. Leverage Web Workers for Heavy Computation

  • For CPU-intensive tasks (like complex calculations or data processing), move the work to a Web Worker. This allows you to run code in the background on a separate thread, preventing the main UI thread from being blocked.
let worker = new Worker('worker.js');
worker.postMessage(data);

14. Minimize DOM Manipulation

  • Manipulating the DOM is expensive. Minimize the number of DOM updates and reflows by:
    • Batch updates (e.g., use documentFragment or innerHTML to make changes all at once).
    • Use requestAnimationFrame for smooth updates.
    • Avoid forced synchronous reflows (e.g., reading layout properties like offsetHeight right after modifying the DOM).

15. Optimize Network Requests

  • Minimize the number of requests (use bundling, lazy loading, etc.), and use techniques like:
    • HTTP/2 for parallel requests.
    • Service workers for caching and offline capabilities.

16. Use Caching Effectively

  • Cache frequently used data to avoid redundant computations. For example, memoize results of expensive function calls if they depend on the same inputs.
function memoize(fn) {
  let cache = {};
  return function (arg) {
    if (cache[arg]) return cache[arg];
    let result = fn(arg);
    cache[arg] = result;
    return result;
  };
}

By following these techniques, you can significantly improve the performance of your JavaScript code, especially in critical parts of your application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment