---
title: "Tech Tip #28: Do it once, outside the loop"
description: "Your loop compiles the same regex a million times."
url: https://greencode.ai/tech-tips/28-do-it-once-outside-the-loop/
---

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

**Your loop compiles the same regex a million times.**

[Watch the video](https://media.greencode.ai/shorts/do-it-once-outside-the-loop-9ede6bc0e2f0.mp4)

Video created by [explainapaper.com](https://explainapaper.com/?utm_source=greencode.ai&utm_medium=film&utm_campaign=made-by)

### 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](https://greencode-constitution.org/?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode) (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)](https://github.com/green-code-initiative/ecoCode?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode): 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](https://greencode.ai/feature/automated-software-maintenance/).

### Tags

#loops#refactoring#python#java

### Sources

- [GreenCode Constitution (Kapenekakis et al., GreenAI workshop, ECML PKDD 2026): invariant computation inside loops in Tier 3](https://greencode.ai/publications/greencode-constitution-agent-principles-for-optimizing-code-and-llm-inference-en/)
- [GreenCode Constitution skill, energy anti-patterns: R2 loop invariant computation: regex, maths, config lookups](https://greencode-constitution.org/skill.md?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode)
- [CISQ, Automated Source Code Green Measure: ASCPEM-PRF-8 expensive operations inside a loop](https://www.it-cisq.org/wiki/cisq-automated-source-code-green-measure/?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode)

[All GreenCode Tech Tips](https://greencode.ai/tech-tips/)

#### Key Facts

- Tip **#28**
- For **Developers**
- Category **Code efficiency**
- Format **short video**
![GreenCode](https://greencode.ai/wp-content/uploads/2024/12/greencode-logo-website-small-colours-2.webp)

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

[Get in touch](https://greencode.ai/contact/)
