@cache # Noncompliant
def cached_function():
...
Python doesn’t have TTL on cache with default libraries.
With functools library @cache acts the same way than @lru_cache(maxsize=None). @lru_cache(maxsize=None) create an unlimited cache and must be a source of memory leak, an unlimited cache can take a lot of RAM / Disk space, resulting to a big energy consumption.
By default, lru_cache set the size of cache to 128 entries.
In this case, the cache is unlimited which is suspect.
@cache # Noncompliant
def cached_function():
...
@lru_cache(maxsize=None) # Noncompliant
def cached_function():
...
@lru_cache() # By default, the max size of the cache is 128
def cached_function():
...
@lru_cache(maxsize=16) # Define a max size to the cache
def cached_function():
...
Measurements were performed using green-code-initiative/EnergyTracer
os: Linux 6.17.0-29-generic
machine: x86_64
chip: Intel® Core™ Ultra 7 255H
RAM: 32 GB
Non compliant Code
from functools import cache
@cache # Noncompliant
def flood_ram(i: int):
return [i] * 150000
for i in range(10):
flood_ram(i)
Compliant code
from functools import lru_cache
@lru_cache(maxsize=5) # Compliant
def flood_ram(i: int):
return [i] * 150000
for i in range(10):
flood_ram(i)
| Metric | With smell | Without smell |
|---|---|---|
Execution Time |
7.33e-3 |
4.83e-3 s |
Average Power |
33.772 W |
37.830 W |
Total Energy |
121.81 J |
89.78 J |
Energy
Box plot
Violin plot
| Metric | Δ mean | p-value | Cohen’s | Effect | Sig. |
|---|---|---|---|---|---|
cpu_mj |
+27.98% |
1.37e-172 |
+4.807 |
large |
✅ |
co2_eq |
+26.74% |
5.43e-165 |
+4.556 |
large |
✅ |
dram_mj |
+26.33% |
2.30e-162 |
+4.475 |
large |
✅ |
time_s |
+34.60% |
5.74e-216 |
+6.209 |
large |
✅ |
Removing the code smell leads to measurable energy differences:
cpu_mj: 28.0% lower energy (Cohen’s d = +4.807, large)
co2_eq: 26.7% lower energy (Cohen’s d = +4.556, large)
dram_mj: 26.3% lower energy (Cohen’s d = +4.475, large)
time_s: 34.6% lower time (Cohen’s d = +6.209, large)
Δ mean = (mean_with − mean_without) / mean_with × 100. Positive → the smell consumes more energy.