JavaScript Reference ยท Practical Pages
JavaScript performance tips
Concept page on JavaScript performance: measure first, choose better algorithms and data structures, avoid repeated work, batch DOM changes and keep the main thread free.
Most JavaScript is fast enough. Performance work pays off when a page feels slow, an animation stutters, or a loop touches thousands of items. The order of work matters: measure to find the slow part, fix the algorithm before the micro-details, and measure again to prove it helped.
This page collects the pitfalls that cause the most trouble in real code. None of them is a reason to make code harder to read before you know it is a bottleneck.
Measure first
Use the browser's Performance panel for the big picture, and performance.now() or console.time() for small experiments. Run the code many times and ignore the first run, because the engine optimizes hot code as it goes. Timing results vary by device, so the examples below count operations instead, which is the same on every machine.
Choose the right algorithm and data structure
Looking up an item in an array with includes() or find() scans from the start: the work grows with the array. A Set or Map finds items in roughly constant time. Nested loops over two lists multiply the work; building a lookup table first turns them into two separate passes.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Avoid repeating the same work
- Move constant work out of loops. Compute
items.length, a regular expression, or a formatter once, not on every pass. Creating anIntl.NumberFormatinside a loop is far slower than reusing one. - Cache expensive pure results (memoization). If a function always returns the same answer for the same input, remember it.
- Do not rebuild strings by hand when
join()works, and preferarray.push()followed by onejoin()over thousands of intermediate arrays.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Caches need a limit or a way to forget entries, otherwise they behave like a memory leak.
Be careful with arrays and objects
shift()andunshift()on big arrays move every element; usepush()/pop()at the end, or an index pointer, for queues.- Spreading in a loop (
acc = [...acc, x]or{ ...acc, [k]: v }) copies the whole structure each time, which makes a loop quadratic. Mutate a local accumulator, or build withpush()and then convert. delete obj[key]can make an object slower to access in some engines; useMapfor dictionaries that change a lot, or set a value toundefined.- Array holes and mixed element types (
[1, "a", {}]) prevent some engine optimizations. Typed arrays are the right tool for numeric data.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Keep the DOM work small
Changing the DOM is much more expensive than changing JavaScript objects, and reading layout values (offsetHeight, getBoundingClientRect()) right after writing styles forces the browser to recalculate layout immediately ("layout thrashing").
- Batch writes: build elements in a
DocumentFragmentor setinnerHTMLonce, not thirty times. - Separate reads from writes: read all measurements first, then write.
- Use CSS for visual effects: animate
transformandopacitywith CSS instead of moving elements with JavaScript each frame. - Use
requestAnimationFrame()for work tied to painting, notsetInterval(). - Event delegation: one listener on a parent beats a thousand listeners on children.
- Throttle or debounce noisy events (
scroll,resize,input), or useIntersectionObserverinstead of measuring in a scroll handler.
Keep the main thread free
JavaScript in a page shares one thread with rendering and input. A long synchronous task freezes the page.
- Split big jobs into chunks and yield between them (
await new Promise(r => setTimeout(r)), orscheduler.yield()where supported). - Move heavy computation to a Web Worker.
- Use
asyncordeferon scripts, and load code only when needed with dynamicimport(). - Prefer streaming and pagination to loading enormous JSON payloads at once.
Usage notes
- Readable first. A clear algorithm beats a clever micro-optimization.
- Beware benchmarks that are too small. The engine may optimize away work whose result you never use.
forloops versusforEach()andmap(): the differences are usually negligible; pick by clarity.- Avoid
try...catchworries. It is not a measurable cost in modern engines. - Memory counts too. Remove event listeners and timers you no longer need, and avoid holding big objects in long-lived variables.
- Ship less JavaScript. Network and parse time often matter more than runtime speed.
- Test on slower devices, not only on your development machine.
Browser support
The techniques here work everywhere. scheduler.yield() and some scheduling APIs are newer and not in every browser, so feature-detect them.