Skip to content

Latest commit

 

History

History
119 lines (69 loc) · 3.82 KB

File metadata and controls

119 lines (69 loc) · 3.82 KB

Code Smell 129 - Structural Optimizations

Code Smell 129 - Structural Optimizations

We love to improve time and space complexity by guessing not real scenarios

TL;DR: Don't optimize anything until you have a real-use scenario benchmark.

Problems

Solutions

  1. Cover your scenarios with tests.

  2. Write readable (and possibly non-performant) code.

  3. Do a real benchmark with real user data. (No, iterating your code 100,000 times might not be a real use case).

  4. If you have conclusive data, you need to improve the benchmark's found bottlenecks using the Pareto principle.

  5. Attack the worst 20% of problems causing 80% bad performance.

Context

In university and online courses, we learn algorithms, data structures, and computational complexity before good design rules.

We tend to overestimate the (possible) performance problems and underestimate code readability and software lifetime.

Premature optimization often has no evidence of solving real problems.

We need to surgically improve our code when the facts tell us we have a real issue.

Sample Code

Wrong

for (k = 0; k < 3 * 3; ++k) {
     i = Math.floor(k / 3);
     j = k % 3;
     console.log(i + ' ' +  j);
  }
 
// This cryptic piece of code iterates a
// two-dimensional array
// You don't have proof this will be useful
// In real contexts

Right

for (outerIterator = 0; outerIterator< 3; outerIterator++) {
    for (innerIterator = 0; innerIterator< 3; innerIterator++) {
        console.log(outerIterator + ' ' + innerIterator);
    }
}

// This is a readable double for-loop
// 3 is a small number
// No performance issues (by now)
// You will wait for real evidence

Detection

[X] Manual

This is a semantic smell.

We might find the code harder to read.

Tags

  • Premature Optimization

Conclusion

We need to stop optimizing for machines and start optimizing for human readers and code maintainers.

We need to avoid programming languages designed for premature optimization and favor robust ones.

Relations

Code Smell 06 - Too Clever Programmer

Code Smell 20 - Premature Optimization

More Info

Credits

Photo by Priscilla Du Preez on Unsplash


Optimism is an occupational hazard of programming: feedback is the treatment.

Kent Beck

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code