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

Transcript

This one-line habit makes your code slow down fast as it grows. It is adding to a string with plus-equals, inside a loop. In many languages, each plus-equals copies everything built so far. So a long report gets copied again, and again, line by line. Double the length, and the copying goes up four times. All that copying costs processor time, and energy. Here is the fix you can use today. Collect the parts in a list, then join them once at the end. In Python, use join. In Java and C sharp, use a StringBuilder. In Go, use strings.Builder. Elsewhere, use a buffer. And look for plus-equals on strings inside loops in code review. GreenCode researchers list building strings in a loop among the worst energy wasters in code. GreenCode's Constitution skill can help an AI coding agent spot and fix this. Then measure before and after, using tools like GreenCode's green-languages. GreenCode helps tackle this by fixing flagged code one piece at a time. It writes missing tests first, then sends each change for a person to approve. That was GreenCode Tech Tip number eighteen. Follow for the next tip, and find more on greencode.ai/tech-tips.

All GreenCode Tech Tips · All GreenCode videos

  • Tip #18
  • For Developers
  • Length 1:16
  • Category Code efficiency
GreenCode

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

Get in touch