Skip to content

Rules/gci22 remove unnecessary method calls#165

Open
Loup-K wants to merge 4 commits into
green-code-initiative:mainfrom
snail-unamur:rules/gci22-remove-unnecessary-method-calls
Open

Rules/gci22 remove unnecessary method calls#165
Loup-K wants to merge 4 commits into
green-code-initiative:mainfrom
snail-unamur:rules/gci22-remove-unnecessary-method-calls

Conversation

@Loup-K
Copy link
Copy Markdown

@Loup-K Loup-K commented May 22, 2026

Summary

This Pull Request provides empirical energy measurements to justify the implementation of the rule GCI22 - The use of methods for basic operations for Python. The rule detects two anti-patterns that bypass Python's optimized bytecode instructions:

  1. Direct dunder method calls — calling a.__add__(b) instead of a + b, x.__eq__(y) instead of x == y, my_list.__len__() instead of len(my_list), etc.
  2. Trivial wrapper functions — defining def add(a, b): return a + b and calling it instead of using + directly at the call site.

Calling a.__add__(b) incurs additional overhead due to attribute lookup and method invocation, whereas a + b is compiled into a dedicated bytecode instruction (BINARY_OP) that dispatches directly through C-level slots, avoiding Python-level method resolution.

Motivation

As part of my UNamur master's degree, I have to open a pull request on the creedengo repository and justify the developed rule with empirical and scientific methods.

Energy Measurements

Measurements were performed on Apple Silicon (macOS) using fstormacq/energyTracer, a cross-platform tool that captures fine-grained per-component energy samples (CPU, GPU, ANE/CO2 eq., DRAM) for a given process.

Code Under Test

The code under test for this experiment was the following:

With the code smell (dunder method calls)
def run_code():
    a = 10
    b = 3
    x = 5
    y = 8
    n1 = 0b1010
    n2 = 0b1100

    result_add = a.__add__(b)
    result_sub = a.__sub__(b)
    result_mul = a.__mul__(b)
    result_div = a.__truediv__(b)
    result_mod = a.__mod__(b)
    result_pow = a.__pow__(b)

    is_equal   = x.__eq__(y)
    is_greater = x.__gt__(y)
    is_less    = x.__lt__(y)
    is_gte     = x.__ge__(y)
    is_lte     = x.__le__(y)
    is_not_eq  = x.__ne__(y)

    my_list = [1, 2, 3, 4, 5]
    size = my_list.__len__()

    words = ["This", "is", "a", "test"]
    found = list.__contains__(words, "test")

    first = "Hello"
    last  = "World"
    greeting1 = first.__add__(", " + last)
    greeting2 = "".join([first, ", ", last])

    flag_a = True
    flag_b = False
    result_and = flag_a.__and__(flag_b)
    result_or  = flag_a.__or__(flag_b)

    bit_and    = n1.__and__(n2)
    bit_or     = n1.__or__(n2)
    bit_xor    = n1.__xor__(n2)
    bit_lshift = n1.__lshift__(2)
    bit_rshift = n1.__rshift__(2)

    repeated_str  = "abc".__mul__(3)
    repeated_list = [0].__mul__(5)

    data     = {"key": 42}
    my_list2 = [10, 20, 30]
    val = data.__getitem__("key")
    my_list2.__setitem__(1, 99)
    my_list2.__delitem__(0)

for _ in range(10000):
    run_code()
Without the code smell (native operators)
def run_code():
    a = 10
    b = 3
    x = 5
    y = 8
    n1 = 0b1010
    n2 = 0b1100

    result_add = a + b
    result_sub = a - b
    result_mul = a * b
    result_div = a / b
    result_mod = a % b
    result_pow = a ** b

    is_equal   = x == y
    is_greater = x > y
    is_less    = x < y
    is_gte     = x >= y
    is_lte     = x <= y
    is_not_eq  = x != y

    my_list = [1, 2, 3, 4, 5]
    size = len(my_list)

    words = ["This", "is", "a", "test"]
    found = "test" in words

    first = "Hello"
    last  = "World"
    greeting1 = first + ", " + last
    greeting2 = f"{first}, {last}"

    flag_a = True
    flag_b = False
    result_and = flag_a and flag_b
    result_or  = flag_a or flag_b

    bit_and    = n1 & n2
    bit_or     = n1 | n2
    bit_xor    = n1 ^ n2
    bit_lshift = n1 << 2
    bit_rshift = n1 >> 2

    repeated_str  = "abc" * 3
    repeated_list = [0] * 5

    data     = {"key": 42}
    my_list2 = [10, 20, 30]
    val = data["key"]
    my_list2[1] = 99
    del my_list2[0]

for _ in range(10000):
    run_code()

Plots

Comparisons

CPU consumption conparison Time energy comparison
cpu_energy_comparison_15 time_energy_comparison_15

Box plots

CPU box plot Time box plot
cpu_moustache_15 time_moustache_15

Violins

CPU violins plot Time violins plot
cpu_violin_15 time_violin_15

Analysis

  • 2 996 612 samples collected with the code smell
  • 2 998 521 samples collected without the code smell
  • Significance level: α = 0.05
Metric Δ mean p-value Cohen's d Effect Significant
cpu_mj +57.05% 0.00e+00 +102.552 large
gpu_mj +55.69% 0.00e+00 +21.791 large
dram_mj +55.13% 0.00e+00 +5.167 large
time_s +54.91% 0.00e+00 +78.352 large

Δ mean = (mean_with − mean_without) / mean_with × 100. A positive value means the smell consumes more energy.

Key Takeaways

  • CPU energy is ~57% higher with the smell — Cohen's d = 102.552 (very large effect), indicating significantly increased computational overhead when basic operations are performed via method calls rather than optimized language constructs.
  • DRAM energy is ~55% higher with the smell — Cohen's d = 5.167 (large effect), reflecting additional memory pressure caused by repeated object handling and method invocation overhead.
  • GPU energy is ~56% higher with the smell — Cohen's d = 21.791 (large effect), suggesting that even non-graphics components are indirectly impacted by the increased workload, though not as the primary bottleneck.
  • Execution time is ~55% higher with the smell — Cohen's d = 78.352 (very large effect), confirming that the overhead of method-based operations significantly slows down execution.

Conclusion

The rule appears to show a noticeable impact when the code smell is repeated a large number of times. However, the relevance of the rule can still be questioned, since the likelihood of this rule actually being triggered in a programmer’s code is relatively low. Even for beginners, it is quite uncommon to write code containing this kind of code smell. In conclusion, the rule may not be as relevant as it initially seems. It depends on how much importance we assign to the energy impact of a rule compared with the importance of how frequently the rule is used.

Dataset

The raw measurements and plots are publicly available on Zenodo:

DOI

How to Reproduce

Measurements can be reproduced using fstormacq/energyTracer on any supported platform.

⚠️ Results may vary across different platforms, hardware, and devices.

@Loup-K Loup-K force-pushed the rules/gci22-remove-unnecessary-method-calls branch from 75af719 to 34c4be2 Compare May 22, 2026 08:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Ready

Development

Successfully merging this pull request may close these issues.

1 participant