global_var = 'foo'
def print_global_var_details():
print(len(global_var)) # Noncompliant
print('Global var : ', global_var) # Noncompliant
print('Global var : ' + global_var) # Noncompliant
print_global_var_details()
Accessing global variables requires scope resolution, which consumes additional CPU cycles. Passing global variables as function parameters treats them as local variables, reducing lookup overhead.
Thus, prefer local variables as parameters.
global_var = 'foo'
def print_global_var_details():
print(len(global_var)) # Noncompliant
print('Global var : ', global_var) # Noncompliant
print('Global var : ' + global_var) # Noncompliant
print_global_var_details()
global_var = 'foo'
def print_var_details(local_var):
print(len(local_var))
print('Var : ', local_var)
print('Var : ' + local_var)
print_var_details(global_var)
Measurements were performed using green-code-initiative/EnergyTracer
os: Linux 6.17.0-23-generic
machine: x86_64
chip: Intel® Core™ Ultra 7 255H
RAM: 32 GB
Non compliant Code
global_var = 'foo'
def print_global_var_details():
print(len(global_var)) # Noncompliant
print('Global var : ', global_var) # Noncompliant
print('Global var : ' + global_var) # Noncompliant
print_global_var_details()
Compliant code
global_var = 'foo'
def print_var_details(local_var):
print(len(local_var))
print('Var : ', local_var)
print('Var : ' + local_var)
print_var_details(global_var)
With smell |
Without smell |
|
Execution Time |
2.0e-4 s |
1.5e-4 s |
Average Power |
259.932 W |
331.044 W |
Total Energy |
25.97 J |
23.99 J |
Energy
Box plot
Violin plot
Metric |
Δ mean |
p-value |
Cohen’s |
Effect |
Sig. |
|
+5.85% |
0.0167 |
+0.156 |
negligible |
✅ |
|
+5.86% |
0.0165 |
+0.156 |
negligible |
✅ |
|
+5.87% |
0.0165 |
+0.156 |
negligible |
✅ |
|
+26.09% |
7.33e-28 |
+0.740 |
medium |
✅ |
Removing the code smell leads to measurable energy differences:
time_s: 26.1% lower time (Cohen’s d = +0.740, medium)
Δ mean = (mean_with − mean_without) / mean_with × 100. Positive → the smell consumes more energy.