JavaScript Memory, Garbage Collection and Performance

Most of the time JavaScript manages memory for you, and most code is fast enough. But long-running apps (dashboards open all day, Node.js servers, test runners executing thousands of tests) slowly use more and more memory when something is never released, and an innocent loop inside a loop can turn a 1-second job into a 10-minute one. Performance testing and memory-leak hunting are also real QA specialities. In this lesson you will learn how memory is allocated and freed, what garbage collection does, the classic causes of leaks and how to avoid them, weak references, how to measure time and memory correctly, and how choosing the right data structure changes performance by orders of magnitude.

Advertisement

📖 What You’ll Learn: the stack and the heap, primitives vs references, reachability and garbage collection, the common memory leaks (globals, timers, listeners, closures, growing caches), WeakMap, WeakSet, WeakRef and FinalizationRegistry, measuring memory with process.memoryUsage, measuring time with performance.now, Big O in practice (array vs Set lookups, nested loops), avoiding blocking the event loop, and performance checks in tests.


🧠 Stack, Heap and References

JavaScript uses two kinds of memory:

  • The stack holds function calls and their local primitive values (numbers, booleans, short strings). It is small and fast, and freed automatically when a function returns.
  • The heap holds objects, arrays, functions and large strings. Variables hold references (addresses) to heap objects.

📄 references.js

let a = 10;
let b = a;          // copies the VALUE
b = 20;
console.log(a, b);

const user = { name: "Asha" };
const sameUser = user;   // copies the REFERENCE: both point to one heap object
sameUser.name = "Ravi";
console.log(user.name, user === sameUser);

⌨️ Terminal

node references.js

🖥️ Output

10 20
Ravi true

The second example is the root of many bugs (and the reason for the immutability techniques in the functional programming lesson): two variables can silently share one object.


♻️ Garbage Collection: Reachability

Definition: the garbage collector (GC) automatically frees heap objects that are no longer reachable: that cannot be reached by following references from the “roots” (global variables, the current call stack, active closures, timers and listeners). You never free memory yourself; you just stop referencing it.

Node.js can expose the garbage collector to show this (the --expose-gc flag is for experiments only):

📄 gc.js

const mb = () => Math.round(process.memoryUsage().heapUsed / 1024 / 1024);

globalThis.gc();
const before = mb();
let report = { rows: Array.from({ length: 1_000_000 }, (_, i) => ({ id: i })) };   // a big object
const during = mb();

report = null;            // drop the only reference: the object is now unreachable
globalThis.gc();
const after = mb();

console.log("grew by more than 30 MB:", during - before > 30);
console.log("freed after GC:", during - after > 30);

⌨️ Terminal

node --expose-gc gc.js

🖥️ Output

grew by more than 30 MB: true
freed after GC: true

📌 Note: V8 (the engine in Chrome and Node.js) uses a generational collector: most objects die young, so new objects are collected often and cheaply, and long-lived ones are moved to an “old space” checked less often. You do not need to tune it; you need to avoid keeping references you no longer need.


🚰 Common Memory Leaks

A memory leak in JavaScript is memory that stays reachable although the program no longer needs it. The usual suspects:

LeakExampleFix
Growing collectionsA cache or log array that only ever growsLimit its size, expire entries, or use WeakMap
Forgotten timerssetInterval never cleared, keeping its closure aliveclearInterval when done
Forgotten listenersListeners added on every render or page visit, never removedremoveEventListener, { once: true }, or AbortController
Accidental globalsresults = [] without let in sloppy modeStrict mode / ES modules, ESLint no-undef
Detached DOM nodesRemoved elements still referenced from JavaScriptDrop references after removing elements
Closures holding big dataA small callback that captures a huge objectCapture only what you need

A growing cache is the most common leak in long-running test runners and servers:

📄 leak.js

const mb = () => Math.round(process.memoryUsage().heapUsed / 1024 / 1024);

// leaky: every response is kept forever
const responseLog = [];
function handleLeaky(i) { responseLog.push({ id: i, body: new Array(200).fill(i) }); }

// fixed: keep only the last 100 entries
const recent = [];
function handleBounded(i) {
  recent.push({ id: i, body: new Array(200).fill(i) });
  if (recent.length > 100) recent.shift();
}

globalThis.gc();
let start = mb();
for (let i = 0; i < 50_000; i++) handleLeaky(i);
globalThis.gc();
console.log("leaky log entries:", responseLog.length, "| grew > 40 MB:", mb() - start > 40);

responseLog.length = 0;
globalThis.gc();
start = mb();
for (let i = 0; i < 50_000; i++) handleBounded(i);
globalThis.gc();
console.log("bounded entries:", recent.length, "| grew > 40 MB:", mb() - start > 40);

⌨️ Terminal

node --expose-gc leak.js

🖥️ Output

leaky log entries: 50000 | grew > 40 MB: true
bounded entries: 100 | grew > 40 MB: false
Advertisement

Timers and listeners keep things alive

📄 cleanup.js

const ac = new AbortController();
const target = new EventTarget();

let ticks = 0;
const timer = setInterval(() => ticks++, 5);              // must be cleared!

// listeners added with a signal are all removed by one abort() call
target.addEventListener("refresh", () => console.log("refresh A"), { signal: ac.signal });
target.addEventListener("refresh", () => console.log("refresh B"), { signal: ac.signal });
target.dispatchEvent(new Event("refresh"));

setTimeout(() => {
  clearInterval(timer);
  ac.abort();                                             // removes both listeners
  target.dispatchEvent(new Event("refresh"));             // nothing logged now
  console.log("timer stopped after a few ticks:", ticks > 3, "| listeners removed");
}, 60);

⌨️ Terminal

node cleanup.js

🖥️ Output

refresh A
refresh B
timer stopped after a few ticks: true | listeners removed

💡 Tip: Find leaks in the browser with DevTools → Memory: take a heap snapshot, repeat an action several times (open and close a dialog, navigate away and back), take another snapshot and compare. Objects whose count keeps growing, or “Detached” DOM nodes, point to the leak.


🪶 Weak References: WeakMap, WeakSet and WeakRef

A normal Map keeps its keys alive. A WeakMap holds its keys weakly: when nothing else references a key object, the entry disappears automatically. It is perfect for attaching extra data to objects you do not own, such as DOM elements or test objects:

📄 weak.mjs

const metadata = new WeakMap();

let page = { url: "/checkout" };
metadata.set(page, { visits: 3, screenshots: ["a.png"] });
console.log(metadata.get(page), metadata.has(page));

// WeakRef: a reference that does not keep the object alive
let bigReport = { rows: new Array(100_000).fill("row") };
const ref = new WeakRef(bigReport);
console.log("still alive:", ref.deref()?.rows.length);

bigReport = null;
page = null;                                      // the WeakMap entry can now be collected too
await new Promise((r) => setTimeout(r, 0));     // WeakRefs stay alive until the current job ends
globalThis.gc();
console.log("after GC:", ref.deref());

⌨️ Terminal

node --expose-gc weak.mjs

🖥️ Output

{ visits: 3, screenshots: [ 'a.png' ] } true
still alive: 100000
after GC: undefined
  • WeakMap/WeakSet keys must be objects, and you cannot list their contents (they may vanish at any time).
  • WeakRef and FinalizationRegistry are advanced tools for caches; the GC decides when (or whether) objects are collected, so never rely on exact timing.

⏱️ Measuring Time Correctly

Use performance.now(), not Date.now(), for timings: it is high-resolution and monotonic (it never jumps when the system clock changes). Measure several runs, because a single run is noisy:

📄 timing.js

function measure(label, fn, runs = 5) {
  const times = [];
  for (let i = 0; i < runs; i++) {
    const start = performance.now();
    fn();
    times.push(performance.now() - start);
  }
  times.sort((a, b) => a - b);
  return { label, median: times[Math.floor(runs / 2)] };
}

const data = Array.from({ length: 200_000 }, (_, i) => i);
const loop = measure("for loop", () => { let s = 0; for (let i = 0; i < data.length; i++) s += data[i]; return s; });
const reduce = measure("reduce", () => data.reduce((s, n) => s + n, 0));

for (const r of [loop, reduce]) console.log(`${r.label}: measured`, typeof r.median === "number" && r.median >= 0);
console.log("both finish in under 100 ms:", loop.median < 100 && reduce.median < 100);

⌨️ Terminal

node timing.js

🖥️ Output

for loop: measured true
reduce: measured true
both finish in under 100 ms: true

Timings vary between machines and runs, which is why the example prints checks instead of milliseconds. In your own measurements print the numbers, and compare medians of several runs, never a single run. For serious benchmarks use a tool such as tinybench or the --cpu-prof flag and DevTools.


Advertisement

📈 Big O in Practice: Choose the Right Structure

Big O describes how work grows with input size. The difference between O(n) and O(1) is invisible with 10 items and enormous with 100,000. Counting operations shows it without depending on machine speed:

📄 bigo.js

const n = 20_000;
const ids = Array.from({ length: n }, (_, i) => `USER-${i}`);
const lookups = Array.from({ length: n }, (_, i) => `USER-${(i * 7) % n}`);

// O(n) per lookup: Array.includes scans the array
let arrayComparisons = 0;
for (const id of lookups) {
  for (const x of ids) { arrayComparisons++; if (x === id) break; }
}

// O(1) per lookup: Set.has uses hashing
const idSet = new Set(ids);
let setLookups = 0;
for (const id of lookups) { setLookups++; idSet.has(id); }

console.log("array comparisons:", arrayComparisons.toLocaleString("en-IN"));
console.log("set lookups:      ", setLookups.toLocaleString("en-IN"));
console.log("array did", Math.round(arrayComparisons / setLookups), "times more work");

⌨️ Terminal

node bigo.js

🖥️ Output

array comparisons: 20,00,10,000
set lookups:       20,000
array did 10001 times more work
OperationCostBetter alternative
array.includes / indexOf / find inside a loopO(n²) overallBuild a Set or Map once, then has/get
array.shift() / unshift() on big arraysO(n) eachUse an index pointer, or push/pop
String += in a huge loopMany temporary stringsCollect parts in an array, then join("")
JSON.parse(JSON.stringify(x)) to copySerialises everythingstructuredClone or copy only what changes
Sorting inside a loopO(n log n) every timeSort once outside the loop

🚦 Do Not Block the Event Loop

JavaScript runs your code on one thread. A long synchronous loop blocks everything else: timers, network responses, and in the browser clicks and rendering. Split heavy work into chunks so the event loop can breathe, or move it to a worker:

📄 blocking.mjs

const work = Array.from({ length: 6 }, (_, i) => `chunk ${i + 1}`);
let ticks = 0;
const heartbeat = setInterval(() => ticks++, 1);         // stands in for UI updates / other requests

const busy = (ms) => { const end = performance.now() + ms; while (performance.now() < end) {} };

// blocking: all chunks in one go
busy(60);
const ticksWhileBlocked = ticks;

// non-blocking: one chunk per macrotask, yielding in between
for (const _ of work) {
  busy(10);
  await new Promise((r) => setTimeout(r, 0));          // let timers and I/O run
}
clearInterval(heartbeat);
console.log("ticks during the 60 ms blocking loop:", ticksWhileBlocked);
console.log("ticks while working in chunks > 0:", ticks - ticksWhileBlocked > 0);

⌨️ Terminal

node blocking.mjs

🖥️ Output

ticks during the 60 ms blocking loop: 0
ticks while working in chunks > 0: true

During the blocking loop not a single timer tick could run. In a browser that means a frozen page; in a Node.js API server it means every other request waits.


🧪 Tester Scenario: Simple Performance Checks in Tests

Functional tests can include cheap performance guards: a time budget for an operation, and a check that repeating an action does not keep growing memory. Use generous budgets (CI machines are slower and noisier) so they catch real regressions, not normal variation:

📄 perf.test.js

const mb = () => process.memoryUsage().heapUsed / 1024 / 1024;

function buildReport(rows) {
  const byStatus = new Map();
  for (const r of rows) byStatus.set(r.status, (byStatus.get(r.status) ?? 0) + 1);
  return Object.fromEntries(byStatus);
}

const rows = Array.from({ length: 300_000 }, (_, i) => ({ id: i, status: i % 10 === 0 ? "failed" : "passed" }));

// 1. time budget
const start = performance.now();
const report = buildReport(rows);
const elapsed = performance.now() - start;
console.log(report);
console.log(elapsed < 500 ? "✓ report built within the 500 ms budget" : `✗ too slow: ${Math.round(elapsed)} ms`);

// 2. no memory growth over repeated runs
globalThis.gc();
const baseline = mb();
for (let i = 0; i < 20; i++) buildReport(rows);
globalThis.gc();
const growth = mb() - baseline;
console.log(growth < 5 ? "✓ no memory growth after 20 runs" : `✗ grew ${growth.toFixed(1)} MB`);

⌨️ Terminal

node --expose-gc perf.test.js

🖥️ Output

{ failed: 30000, passed: 270000 }
✓ report built within the 500 ms budget
✓ no memory growth after 20 runs

For web pages, Playwright can read the browser’s Navigation Timing and Web Vitals through page.evaluate(() => performance.getEntriesByType("navigation")), and Lighthouse or k6 handle full performance and load testing.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Predict the output, then run it: does changing copy change original?

const original = { tags: ["smoke"] };
const copy = original;
copy.tags.push("ui");
Show answer

📄 practice1.js

const original = { tags: ["smoke"] };
const copy = original;
copy.tags.push("ui");
console.log(original.tags, original === copy);

🖥️ Output

[ 'smoke', 'ui' ] true

Yes: copy is a second reference to the same object.

Q2. Write a cache function that keeps at most 3 entries, dropping the oldest.

Show answer

📄 practice2.js

function createCache(limit) {
  const map = new Map();
  return {
    set(k, v) {
      map.delete(k);
      map.set(k, v);
      if (map.size > limit) map.delete(map.keys().next().value);   // oldest = first inserted
    },
    keys: () => [...map.keys()],
  };
}
const cache = createCache(3);
["a", "b", "c", "d", "e"].forEach((k) => cache.set(k, k.toUpperCase()));
console.log(cache.keys());

🖥️ Output

[ 'c', 'd', 'e' ]

Q3. Find the duplicate test IDs in a list efficiently (one pass) using a Set.

Show answer

📄 practice3.js

const ids = ["TC1", "TC2", "TC3", "TC2", "TC4", "TC1"];
const seen = new Set();
const dupes = new Set();
for (const id of ids) (seen.has(id) ? dupes : seen).add(id);
console.log([...dupes]);

🖥️ Output

[ 'TC2', 'TC1' ]

Q4. Use an AbortController to add three listeners and remove all of them with one call.

Show answer

📄 practice4.js

const target = new EventTarget();
const ac = new AbortController();
for (const n of [1, 2, 3]) target.addEventListener("ping", () => console.log("listener", n), { signal: ac.signal });
target.dispatchEvent(new Event("ping"));
ac.abort();
target.dispatchEvent(new Event("ping"));
console.log("done");

🖥️ Output

listener 1
listener 2
listener 3
done

Q5. Build a 10,000-line string efficiently with an array and join, and print its length.

Show answer

📄 practice5.js

const lines = [];
for (let i = 1; i <= 10_000; i++) lines.push(`row ${i}`);
const csv = lines.join("\n");
console.log(csv.length, csv.split("\n").at(-1));

🖥️ Output

88893 row 10000

Q6. A dashboard tab becomes slow after being open for a day. What would you check?

Show answer

Take heap snapshots in DevTools → Memory before and after repeating typical actions and compare object counts; look for detached DOM nodes, arrays or maps that keep growing (logs, caches, chart data), intervals that are never cleared (polling), and listeners added on every refresh. Also check the Performance panel for long tasks blocking the main thread.


🧠 MCQ Quiz: Memory and Performance

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Where are objects and arrays stored?
  2. When does the garbage collector free an object?
  3. Which is a typical memory leak?
  4. What keeps a setInterval callback’s closure alive?
  5. What is special about WeakMap keys?
  6. Which function should you use to time code?
  7. Why measure several runs?
  8. What is the complexity of looking up an item with array.includes inside a loop over another array of the same size?
  9. What happens when a long synchronous loop runs in the browser?
  10. How can one call remove many event listeners?

💼 Interview Questions and Answers

Q1. How does garbage collection work in JavaScript?

The engine periodically finds all objects reachable from roots (globals, the stack, closures, timers, listeners) by following references (mark), and frees the rest (sweep). V8 uses a generational approach: frequent, fast collections of young objects and less frequent ones of long-lived objects. Developers do not free memory explicitly; they make objects unreachable by dropping references.

Q2. What causes memory leaks in JavaScript applications and how do you find them?

Unbounded caches and logs, intervals and listeners that are never removed, detached DOM nodes still referenced in code, closures capturing large objects, and accidental globals. Find them by repeating an action and comparing heap snapshots in DevTools (or --inspect for Node.js), watching memory over time with the Performance monitor, and looking for growing object counts or detached nodes.

Q3. How would you add a performance check to an automated test suite?

Measure specific operations with performance.now() or page timings from the Navigation Timing API, compare against generous budgets to avoid flakiness, track trends over time instead of failing on small changes, run them in a stable environment, and keep full load and performance testing in dedicated tools such as k6, JMeter or Lighthouse CI.

Q4. Why can Set.has be much faster than Array.includes?

includes scans elements one by one, O(n). A Set is a hash table: has computes a hash and checks one bucket, O(1) on average. Inside a loop over n items, that is the difference between O(n²) and O(n): negligible for 100 items, minutes vs milliseconds for hundreds of thousands.


Advertisement

❓ Frequently Asked Questions

🤔 Do I need to free memory manually in JavaScript?

No. Set references to null or let variables go out of scope, and the garbage collector does the rest. You only need to avoid keeping references you no longer need.

🤔 What is the –max-old-space-size flag?

It raises Node.js’s heap limit, for example node --max-old-space-size=4096 script.js. It can help with legitimately large data, but it hides leaks instead of fixing them.

🤔 Is a for loop faster than map or forEach?

Sometimes slightly, but rarely enough to matter. Choose readability first, measure, and optimise only proven hot spots; algorithm and data-structure choices matter far more.

🤔 What are Web Workers?

Browser threads that run JavaScript in the background without blocking the page. Node.js has worker_threads for the same purpose. They are used for heavy computation such as parsing large files.


🏁 Summary

  • Primitives are copied by value; objects live on the heap and variables share references to them.
  • The garbage collector frees unreachable objects; leaks are objects that stay reachable by mistake.
  • Bound caches, clear timers, remove listeners (AbortController helps), and use WeakMap for per-object metadata.
  • Time with performance.now() over several runs; count operations to reason about Big O; prefer Set/Map lookups.
  • Do not block the event loop; add generous time and memory guards to tests and use dedicated tools for load testing.

Next, continue with Lesson 67: Design Patterns.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in