DEV Community

Cover image for Code Smell 129 - Structural Optimizations
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

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 possible 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 benchmark's found bottlenecks using Pareto principle.

  5. Attach the worst 20% problem causing 80% bad performance.

Context

At 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
//We don't have proofs this will be useful
//In real contexts
Enter fullscreen mode Exit fullscreen mode

Right

for (innerIterator = 0; innerIterator < 3; innerIterator