---
title: "Tech Tip #18: Don't build strings with += in a loop"
description: "This one-line habit makes your code quadratically slow."
url: https://greencode.ai/tech-tips/18-dont-build-strings-in-a-loop/
---

# Tech Tip #18: Don't build strings with += in a loop

**This one-line habit makes your code quadratically slow.**

[Watch the video](https://media.greencode.ai/shorts/dont-build-strings-in-a-loop-0779e08c22be.mp4)

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

### The problem

In many languages each += on a string copies everything built so far into a new string. Build a report line by line and the copying grows with the square of its length.

### The fix you can use today

- Collect the parts in a list and join once: ''.join(parts) in Python.
- Use StringBuilder in Java and C#, strings.Builder in Go, a buffer elsewhere.
- Look for += on strings inside loops in code review.

GreenCode researchers list building strings in a loop among the worst energy wasters in code.

### 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
- [green-languages](https://github.com/PLEnergyDev/green-languages?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode) (GreenCode researchers): a command-line tool that measures the energy of whole programs or marked sections of code, across languages

### How GreenCode helps

GreenCode helps tackle this by refactoring flagged code one element at a time. It writes any missing tests and documentation first, and returns every change as a pull request for a person to approve. [More on this](https://greencode.ai/feature/automated-software-maintenance/).

### Tags

#algorithms#loops#python#java

### Sources

- [GreenCode Constitution (Kapenekakis et al., GreenAI workshop, ECML PKDD 2026): quadratic string concatenation among the Tier 1 anti-patterns](https://greencode.ai/publications/greencode-constitution-agent-principles-for-optimizing-code-and-llm-inference-en/)
- [GreenCode Constitution skill, energy anti-patterns: C3 string concatenation in loops](https://greencode-constitution.org/skill.md?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode)

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

#### Key Facts

- Tip **#18**
- 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/)
