Interview Q&A · JavaScript · 12 questions in this topic
Performance & Memory — JavaScript Interview Q&A
Fast JavaScript — rendering performance, bundle cost, GC behavior and measurement discipline. Part of Performance & Memory · 204 questions in the JavaScript bank.
How do you find what is slow (measure-first workflow)?
Answer
Profile before optimizing: DevTools Performance (flame charts, long tasks), Lighthouse/Web-Vitals (field + lab), memory snapshots (retention paths), and bundleanalyzer for bytes. One bottleneck at a time, re-measure every change.
Flame-first beats guess-first every time.
Key points
- 1Profile — flame charts, long tasks.
- 2Field — Core Web Vitals (LCP/INP/CLS).
- 3Bytes — bundle analysis.
💡 INP-plus-LCP-plus-CLS is the vitals trio to name.
How do you reduce bundle size (code-splitting, tree-shaking)?
Answer
Route-level dynamic import() splits, named ESM exports shake, sideEffects flags guide bundlers, dependency audits (one date lib, not three) cut vendor weight, and compression (brotli) plus caching headers finish delivery. Budget via performance budgets in CI.
Split-routes, shake-dead, audit-vendor is the bytes doctrine.
Example
const Admin = lazy(() => import('./Admin.js')); // route split
💡 Dynamic-import-at-routes is the highest-leverage split.
How do virtualized lists handle huge datasets?
Answer
Render only visible rows (windowed) with measured/estimated heights, recycling DOM nodes on scroll — 100k rows feel like 20. Libraries (react-window, TanStack Virtual) handle measurement, overscan and dynamic heights.
Window-visible-only is the virtualization principle.
Example
// TanStack Virtual sketch: rows absolute-positioned in a tall spacerHow does garbage collection work (reachability, generations)?
Answer
Mark-and-sweep frees unreachable objects; generational GC (young/old spaces) collects short-lived garbage cheaply and promotes survivors. Closures, timers and listeners extend reachability — leaks are retention, not lost pointers.
Retention-not-visibility governs everything.
Key points
- 1Reachability — roots outward marking.
- 2Generations — young cheap, old rare.
- 3Leaks — unintended retention paths.
How do you find memory leaks (heap snapshots)?
Answer
Snapshot-compare (allocate, act, release, snapshot-diff retained), watch detached DOM trees, listener/timer counts, and allocation timelines for growth shapes. Three-snapshot technique isolates the leak to an action.
Diff-retained-after-release is the leak-hunting loop.
Example
// DevTools: snapshot → interact → snapshot → compare (detached nodes?)💡 Detached-DOM-plus-listeners is the first suspect.
How do `WeakMap`/`WeakRef` help memory-sensitive caches?
Answer
WeakMap entries vanish with keys (metadata without retention); WeakRef observes without preventing collection (caches deref-checked before use, with FinalizationRegistry cleanup hooks). Strong caches need explicit eviction (LRU); weak ones self-clean.
Weak-for-metadata, LRU-for-caches is the split.
Example
const meta = new WeakMap(); // per-object data, GC-safe // const ref = new WeakRef(big); // observe without retaining
How do hidden classes and inline caches make JS fast (and what breaks them)?
Answer
Stable object shapes share hidden classes (fast property offsets); inline caches memorize lookup sites per shape (monomorphic = fastest). Breaking: adding/deleting properties post-hoc, mixed shapes at one call site (megamorphic), arguments-object abuse.
Construct-fully-then-use, same-order-everywhere is the shape discipline.
Key points
- 1Shapes — shared offsets for stable layouts.
- 2Caches — per-site shape memory.
- 3Breakers — delete, late-adds, mixed shapes.
Example
// fast: same init order // const p = (x, y) => ({ x, y }); // slow: delete p.x; p.z = 1; // shape change
💡 Init-order-consistency is the actionable rule.
How do you optimize re-renders (React memoization)?
Answer
memo skips identical-props renders, useMemo caches computations, useCallback stabilizes function identity, keyed lists reconcile minimally, and state colocation shrinks render scope. Measure with profiler before memoizing — memo has its own comparison cost.
Stable-references-plus-narrow-scope is the re-render doctrine.
Example
// const MemoRow = memo(Row); // skip on same props // const fn = useCallback(() => {}, []); // stable identity
💡 Profile-before-memo is the discipline caveat.
How do images, fonts and third-parties affect performance?
Answer
Images: modern formats (AVIF/WebP), responsive srcset/sizes, lazy loading, explicit dimensions (CLS defense). Fonts: display:swap, subsetting, preloading critical faces. Third-parties: facade/defer, sandbox iframes, budget per vendor.
Dimensions-plus-lazy-plus-swap covers the media story.
Example
<!-- <img src='a.avif' loading='lazy' width='800' height='600'> -->
How do service workers and caching strategies work?
Answer
Service workers intercept fetches with programmable strategies: cache-first (static assets), network-first (fresh data), stale-while-revalidate (instant + background refresh). Versioned caches plus cleanup prevent storage bloat; scope discipline avoids hijacking.
Strategy-per-resource-type is the caching design.
Key points
- 1Cache-first — immutable static.
- 2Network-first — fresh data.
- 3SWR — instant with background refresh.
How do you keep animations at 60fps?
Answer
Animate transform/opacity only (compositor thread, no layout), rAF-scheduled updates, will-change sparingly (layer promotion cost), reduced-motion respect, and work budgeting per frame (~8ms JS to leave headroom).
Compositor-props-plus-frame-budget is the smoothness formula.
Example
// el.animate([{ transform: 'translateX(0)' }, // { transform: 'translateX(100px)' }], { duration: 300 });
💡 prefers-reduced-motion support is the accessibility pairing.
What is the single biggest frontend performance win usually?
Answer
Shipping less JavaScript (split, shake, audit vendors) — parse/compile blocks interactivity on real devices far more than micro-opts. Second: images sized and lazy. Third: render-path discipline (memo, virtualize, composite-only).
Bytes-first is the empirically-correct priority.
Key points
- 1Bytes — less JS, split routes.
- 2Media — sized, modern, lazy.
- 3Render — memoize, virtualize.
Recommended resourcesAffiliate links · may earn us a commission