Tech Tip #28: Do it once, outside the loop

Your loop compiles the same regex a million times.

Video created by explainapaper.com

The problem

Anything computed inside a loop is multiplied by its length. Compiling a regular expression, reading a config value or recalculating a constant on every pass is pure waste.

The fix you can use today

  • Move values that do not change between iterations above the loop.
  • Compile patterns and look up settings once.
  • Cache the result of an expensive call when the inputs repeat.

GreenCode researchers list repeated work inside loops as an energy waste to fix.

Tools that help

  • GreenCode Constitution skill (GreenCode researchers): open-source energy principles and a catalogue of 37 energy anti-patterns that an AI coding agent can follow to find and fix waste like this
  • Creedengo (formerly ecoCode): static analysis rules that flag energy code smells in Java, Python, PHP, JavaScript, C# and Rust

How GreenCode helps

GreenCode helps tackle this by rewriting flagged code one piece at a time. It writes any missing tests first, and returns every change for a person to approve. More on this.

Tags

#loops#refactoring#python#java

Sources

All GreenCode Tech Tips

  • Tip #28
  • For Developers
  • Category Code efficiency
  • Format short video
GreenCode

Want this checked on your own system? Talk to the GreenCode team.

Get in touch