Skip to main content Accessibility Feedback

Don't prematurely optimize for performance

I get a lot of questions around web performance, and specifically, around the relative performance between different approaches. That includes things like…

  • Should I use querySelector() or getElementById()?
  • Should I use a for...of loop or forEach()?
  • Should I attach events on individual elements or use event delegation?

Caring about web performance is great! More developers in our industry should.

But focusing on tiny optimizations like this too early in the process can derail you from actually writing working code.

👋 Pssst! This article is one of the bonus Q&A videos/articles from the new JavaScript Essentials workshop. Registration is open now (and closes in a few weeks, so don’t miss out).

And unless you’re writing code that runs tens of thousands of operations a second, these small performance differences aren’t likely to make any perceivable difference on performance, anyways.

For example, getElementById() is more than twice as fast as the querySelector() method. But the querySelector() method can still run 7 million operations per second in the latest version of Chrome. That’s not slow, even if it’s slower than another method. Switching methods is unlikely to yield any meaningful performance gains unless you’re doing incredibly high volume operations.

So what kinds of things do matter for performance?

  1. Loading lots of JavaScript when just a little will do. JavaScript blocks rendering, so less is better.
  2. JavaScript that triggers lots of repaints and reflows. It’s typically better to inject a bunch of elements once than one element at a time in sequence.
  3. Memory allocation. The more data you store in memory (active variables, event listeners, and so on), the slower your site gets, especially on older devices.