Course contentsShow
← Web Development
Lesson 2073 of 2,98238. JavaScript Performance in the BrowserFree lesson

Optimizing Heavy Computations

Strategies for reducing long task duration: algorithm optimization, caching, and avoiding unnecessary work.

Optimizing Heavy Computations

What you'll learn: How to make expensive calculations faster through smart coding strategies that minimize work and maximize efficiency.

The Problem with Heavy Computations

Even after breaking up long tasks with setTimeout or scheduler.yield(), the computation itself might still take too long. Splitting a slow algorithm into chunks helps responsiveness, but doesn't make the work faster. This is where computation optimization comes in.

Three Core Strategies

1. Algorithm Optimization

Choose smarter algorithms that do less work. A nested loop checking every item against every other item (O(n²)) can often be replaced with a Set lookup (O(n)). The algorithm you choose matters more than micro-optimizations.

// Slow: O(n²) - checks every combination
function findDuplicates(arr) {
  const dupes = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) dupes.push(arr[i]);
    }
  }
  return dupes;
}

// Fast: O(n) - single pass with Set
function findDuplicatesFast(arr) {
  const seen = new Set();
  const dupes = new Set();
  for (const item of arr) {
    if (seen.has(item)) dupes.add(item);
    seen.add(item);
  }
  return Array.from(dupes);
}

2. Caching Results

Store expensive computation results. If the input hasn't changed, reuse the previous result instead of recalculating.

let cachedResult = null;
let cachedInput = null;

function expensiveCalculation(input) {
  if (input === cachedInput) {
    return cachedResult; // Skip the work!
  }
  
  // Do expensive work only when needed
  cachedResult = /* complex calculation */;
  cachedInput = input;
  return cachedResult;
}

3. Avoiding Unnecessary Work

Question every operation: does this need to run now? Can it be skipped entirely?

Key Takeaway: Before breaking tasks into chunks, optimize the computation itself—choose better algorithms, cache results, and eliminate unnecessary work to reduce the total time spent computing.