JavaScript Performance Optimization Techniques Quiz

JavaScript
0 Passed
0% acceptance

Answer 35 questions on minimizing reflows, debouncing/throttling, faster loops, efficient structures, avoiding leaks, web workers, lazy loading, caching, cutting re-renders, and profiling with DevTools.

35 Questions
~70 minutes
1

Question 1

Why do repeated style reads and writes in sequence hurt performance?

A
They trigger layout thrashing because the browser must recalculate styles between each mutation
B
They skip the GPU pipeline
C
They automatically clear caches
D
They freeze requestAnimationFrame
2

Question 2

What prints and why?

javascript
const el = document.getElementById('box')
const width = el.offsetWidth
el.style.width = width + 10 + 'px'
const height = el.offsetHeight
console.log(width, height)
A
Current width then height but with extra forced reflows due to alternating read/write
B
New width is logged twice
C
Only height prints
D
Throws TypeError
3

Question 3

How does batching DOM writes help performance?

A
It allows the browser to apply multiple changes in one layout pass instead of recalculating after each mutation
B
It compiles HTML to WebAssembly
C
It disables garbage collection
D
It hides elements
4

Question 4

Why is translating elements with CSS transforms often cheaper than changing top/left?

A
Transforms can use the compositor without triggering layout, whereas top/left adjusts layout flow
B
Transforms reduce memory size
C
top/left are GPU-only properties
D
Transforms disable hit testing
5

Question 5

What prints?

javascript
const log = []
const handle = _.debounce(() => log.push(Date.now()), 200)
handle(); handle(); handle()
setTimeout(() => console.log(log.length), 400)
A
1
B
2
C
3
D
0
6

Question 6

Why use throttling on scroll handlers?

A
It limits how often costly logic runs despite rapid native events, preventing main-thread saturation
B
It cancels scroll
C
It improves CSS specificity
D
It automatically debounces clicks
7

Question 7

What logs?

javascript
const throttled = _.throttle(() => console.log('tick'), 100)
let count = 0
const timer = setInterval(() => {
  throttled()
  if (++count === 5) clearInterval(timer)
}, 20)
A
tick logs roughly every 100ms, so about 2 times before clear
B
tick logs 5 times
C
tick never logs
D
tick logs continuously without throttling
8

Question 8

How can debouncing improve autocomplete UX?

A
It waits for pause in input before hitting APIs, reducing redundant network calls while still reacting quickly
B
It caches HTML templates
C
It disables keyboard input
D
It queues events indefinitely
9

Question 9

What prints?

javascript
const arr = new Array(1_000_000).fill(0)
console.time('loop')
for (let i = 0, len = arr.length; i < len; i++) {}
console.timeEnd('loop')
A
loop: Xms where caching length avoids repeated property lookups
B
loop: undefined
C
loop: NaN
D
Throws ReferenceError
10

Question 10

Why might for-of be slower than traditional for loops in tight hot paths?

A
for-of creates iterators and uses protocol overhead, while simple for loops use numeric indexes
B
for-of is multithreaded
C
for loops prevent GC
D
for-of skips elements
11

Question 11

What prints?

javascript
const data = [...Array(5)].map((_, i) => i)
console.log(data.reduce((sum, value) => sum + value, 0))
A
10
B
15
C
5
D
Throws TypeError
12

Question 12

How does chunking long loops via requestAnimationFrame help?

A
It breaks work into frames, keeping UI responsive and letting rendering happen between chunks
B
It removes GC costs
C
It locks the main thread
D
It automatically parallelizes loops
13

Question 13

Why can Maps be faster than plain Objects for frequent inserts/deletes?

A
Maps are optimized for dynamic keys without rehashing property order and provide predictable iteration order
B
Objects cannot hold strings
C
Maps store data on the GPU
D
Objects leak memory by default
14

Question 14

What prints?

javascript
const cache = new Map()
cache.set('a', 1)
cache.set('b', 2)
cache.delete('a')
console.log(cache.size, cache.has('a'))
A
1 false
B
2 true
C
0 false
D
Throws TypeError
15

Question 15

When do typed arrays provide optimization benefits?

A
When processing large numeric datasets that benefit from contiguous memory and lower-level operations
B
When storing DOM nodes
C
When holding strings
D
When using JSON.parse
16

Question 16

Why are WeakMaps helpful for caching metadata about DOM nodes?

A
Keys are weakly referenced, so when DOM nodes are removed, cache entries can be garbage-collected automatically
B
WeakMaps serialize to JSON easily
C
WeakMaps replace CSS classes
D
WeakMaps prevent reflows
17

Question 17

Which scenario commonly causes leaks in single-page apps?

A
Leaving event listeners bound to DOM nodes after those nodes are removed
B
Using const for variables
C
Using CSS modules
D
Declaring arrow functions
18

Question 18

What prints?

javascript
function createListener(node) {
  const handler = () => {}
  node.addEventListener('click', handler)
  return { release() { node.removeEventListener('click', handler) } }
}
const button = document.createElement('button')
const tracker = createListener(button)
tracker.release()
console.log(getEventListeners(button).click?.length || 0)
A
0, indicating cleanup prevents leaks
B
1 because removeEventListener fails
C
Throws TypeError
D
undefined since listeners persist
19

Question 19

How can closures cause leaks in long-lived timers?

A
If setInterval retains references to large objects in its callback, those objects cannot be GC’d until the interval clears
B
Closures always leak by design
C
Timers run on another process
D
Closures disable GC
20

Question 20

Why does observing heap snapshots help locate leaks?

A
Snapshots reveal retained objects over time, letting you inspect DOM nodes or closures that stay referenced unexpectedly
B
Snapshots auto-delete leaked nodes
C
Snapshots disable JS execution
D
Snapshots convert code to WASM
21

Question 21

What prints?

javascript
const worker = new Worker('worker.js')
worker.postMessage({ size: 1e7 })
worker.onmessage = (event) => {
  console.log('done', event.data.duration)
}
A
done <duration>, showing heavy computation finishing off main thread
B
Main thread blocks until worker finishes
C
Throws ReferenceError because Worker unsupported
D
No output since workers cannot postMessage back
22

Question 22

Why are workers suited for CPU-heavy parsing?

A
They move computation off the main thread, avoiding UI freezes
B
They access DOM directly
C
They bypass security policies
D
They automatically optimize memory
23

Question 23

What is the cost of using Web Workers?

A
Message serialization overhead and lack of direct DOM access mean data must be copied or transferred
B
They double network requests
C
They require TypeScript
D
They disable caching
24

Question 24

What prints?

javascript
// inside worker.js
self.onmessage = ({ data }) => {
  const start = performance.now()
  let total = 0
  for (let i = 0; i < data.size; i++) total += i
  self.postMessage({ duration: performance.now() - start, total })
}
A
Worker responds with total and duration once computation completes
B
Worker blocks DOM updates
C
Worker cannot use performance.now
D
Worker cannot loop
25

Question 25

How does lazy loading images improve performance?

A
It defers loading offscreen images until they near the viewport, reducing initial bandwidth and paint cost
B
It preloads all images immediately
C
It forces synchronous layout
D
It disables caching
26

Question 26

When should dynamic import() be combined with IntersectionObserver?

A
When you only need a component/scripts once a user scrolls to a section, reducing upfront JS cost
B
When code must run before DOM ready
C
When wanting synchronous modules
D
When avoiding tree shaking
27

Question 27

Why is prefetching different from lazy loading?

A
Prefetch downloads assets ahead of need when idle, while lazy loading waits until demand is certain
B
Prefetching always blocks rendering
C
Lazy loading runs before page load
D
Prefetch is only for CSS
28

Question 28

What prints?

javascript
const memoize = (fn) => {
  const cache = new Map()
  return (key) => {
    if (cache.has(key)) return cache.get(key)
    const result = fn(key)
    cache.set(key, result)
    return result
  }
}
const slowDouble = memoize((n) => n * 2)
console.log(slowDouble(5), slowDouble(5))
A
10 10 with second call served from cache
B
10 undefined
C
undefined undefined
D
Throws TypeError
29

Question 29

Why must cache invalidation be planned?

A
Stale cached data can cause incorrect UI or logic, so rules must specify when to refresh or evict entries
B
Caches increase bandwidth
C
Caches mutate source code
D
Caches prevent SSR
30

Question 30

How does request-level caching help APIs?

A
It deduplicates identical concurrent requests, serving all callers once the first promise resolves
B
It repeats requests twice for safety
C
It blocks caching headers
D
It disables retries
31

Question 31

Why is memoizing selectors popular in state management libraries?

A
Memoized selectors only recompute derived data when inputs change, reducing unnecessary component work
B
They automatically serialize state
C
They prevent action dispatches
D
They remove need for reducers
32

Question 32

What prints?

javascript
const App = () => {
  const [count, setCount] = useState(0)
  const memoizedValue = useMemo(() => expensiveCalc(count), [count])
  console.log('render', memoizedValue)
  return <button onClick={() => setCount(count + 1)}>{count}</button>
}
A
expensiveCalc runs only when count changes, reducing renders that depend on derived value
B
expensiveCalc never runs
C
useMemo triggers reflow
D
useMemo blocks state updates
33

Question 33

How does shouldComponentUpdate or React.memo help performance?

A
They skip re-rendering components when props/state are unchanged, preventing wasted diffing work
B
They remove components from DOM
C
They auto-throttle network
D
They disable hooks
34

Question 34

Why is splitting state into smaller pieces beneficial?

A
Updating localized state reduces the number of components that need to re-render, keeping the UI responsive
B
It doubles bundle size
C
It forces rerender of all children
D
It disables memoization
35

Question 35

How does the Performance panel in DevTools assist optimization?

A
It records flame charts showing scripting, rendering, and painting time, helping pinpoint long tasks and layout thrashes
B
It automatically rewrites code
C
It only monitors network bytes
D
It disables garbage collection

QUIZZES IN JavaScript