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

This one-line habit makes your code quadratically slow.

Video created by explainapaper.com

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 (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 (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.

Tags

#algorithms#loops#python#java

Sources

All GreenCode Tech Tips

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

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

Get in touch