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

Transcript

Your loop compiles the same regex a million times. Anything inside a loop happens once for every pass. So its cost is multiplied by the length of the loop. Compiling a search pattern, reading a setting, or working out a constant. If it never changes between passes, doing it again is pure waste. Here is the fix you can use today. Move values that do not change up, above the loop. Compile patterns and look up settings once. Cache the result of a slow call when the inputs repeat. Now the work happens once, not a million times. GreenCode researchers list repeated work inside loops as an energy waste to fix. GreenCode's Constitution skill can help an AI coding agent find and fix this. Tools like Creedengo also flag energy code smells in six languages. GreenCode helps tackle this by rewriting flagged code one piece at a time. It writes missing tests first, and a person approves every change. That was GreenCode Tech Tip number twenty-eight. Follow for the next tip, and find more on greencode.ai/tech-tips.

All GreenCode Tech Tips · All GreenCode videos

  • Tip #28
  • For Developers
  • Length 1:08
  • Category Code efficiency
GreenCode

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

Get in touch