Premature Optimization

Optimizing before it’s needed.

“Premature optimization is the root of all evil.” – Donald Knuth

Focusing on performance at the expense of readability, before measuring.

Signs of Use (Symptoms)

  • Obscure algorithms used for simple data sets (e.g., bitwise ops instead of math).
  • Caching everything “just in case”.
  • Unreadable code justified by “it’s faster”.

Why it is bad (Consequences)

  • Complexity: Optimized code is often harder to read and maintain.
  • Bugs: Optimization adds edge cases (cache invalidation is hard).
  • Wasted Effort: You might be optimizing a part of the code that only runs 1% of the time.

Why it happens (Root Cause)

Developers want to write “efficient” code and guess where bottlenecks are.

When it might be okay (Exceptions)

  • Core library paths known to be hot (e.g., game loop rendering).

Explanation

Problem

You write a custom implementation of a sort algorithm because “bubble sort is slow”, for a list of 5 items.

The Flaw

The maintenance cost is high, and the speed gain is 0.0001ms.

Real world analogy

Buying a Formula 1 car to drive to the grocery store because it’s “faster”. The setup and maintenance make it slower overall.

Refactoring Solution

  • Measure first: Use a profiler.
  • Optimize later: Only optimize the actual bottlenecks.
  • Clean Code: Readable code is easier to optimize later than optimized code is to read.

Pros and Cons (of the Antipattern)

Pros (Why people do it) Cons (The price you pay)
  • Feels smart
  • Unreadable code
  • Bugs
  • Comparison

    • Related Antipatterns: Complicated Code.
    • Related Principles: YAGNI, KISS.

    Code example

    Typescript

    Bad (The Antipattern)

    Good (The Fix)

    PHP

    Bad (The Antipattern)

    Good (The Fix)