Memoization is awesome. Let's abuse it.
TL;DR: Don't apply premature optimization too early
Memoization can help you improve the performance of recursive functions involving redundant computations but compromise code readability and maintainability.
It would help if you only used it with strong factual evidence on real business case scenarios.
memo = {}
def factorial_with_memo(n):
if n in memo:
return memo[n]
if n == 0:
return 1
result = n * factorial_with_memo(n-1)
memo[n] = result
return result
# This function optimizes the computation of factorials
# by storing previously computed values,
# reducing redundant calculations
# and improving performance for large inputs.
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
You can search for all places where you are using this technique and validate if they are worth it.
Unless you explicitly ask the IAs to use this technique, they will suggest cleaner solutions.
ChatGPT, Gemini, and Claude.ai detect some problems with this technique but do not mention readability as a concern.
It would be best if you kept a balance between performance optimization and code clarity.
You can consider alternatives such as iterative approaches or algorithmic optimizations since memoization significantly compromises code readability.
Code Smell 06 - Too Clever Programmer
Code Smell 20 - Premature Optimization
Code Smells are my opinion.
Photo by Steffen Lemmerzahl on Unsplash
A cache with a bad policy is another name for a memory leak.
Rico Mariani
Software Engineering Great Quotes
This article is part of the CodeSmell Series.