Claude Code performance

Memory Overflow from String Concatenation in Loop

Processing large files or datasets causes out-of-memory errors. Profiling shows massive string accumulation. The issue: concatenating strings in a loop creates new string object each iteration.

Simple string concatenation is inefficient when done repeatedly.

Error Messages You Might See

java.lang.OutOfMemoryError: Java heap space Memory usage spikes when processing large data Application crashes with string concatenation
java.lang.OutOfMemoryError: Java heap spaceMemory usage spikes when processing large dataApplication crashes with string concatenation

Common Causes

  1. Using += in loop to build strings: str += item creates new object each iteration
  2. String concatenation inside tight loop processing millions of items
  3. No buffer/accumulator, just repeatedly building larger strings
  4. Serialization to JSON or XML using simple string concatenation
  5. Log message building with repeated concatenation

How to Fix It

Use StringBuilder (Java) or StringBuffer for accumulation: StringBuilder sb = new StringBuilder(); sb.append(item). In loops: always use StringBuilder. For JSON: use library like Jackson, Gson. For logging: use parameterized messages: log.info("Item: {}", item) not "Item: " + item. Test with large data: if memory spikes, likely concatenation issue.

Real developers can help you.

You don't need to be technical. Just describe what's wrong and a verified developer will handle the rest.

Get Help

Frequently Asked Questions

Why is += slow in loops?

Each += creates new String. For 1000 items: creates 1000 intermediate strings. StringBuilder creates 1 string.

How much faster is StringBuilder?

10-100x faster for 1000s of concatenations. Order of magnitude better for large datasets.

When should StringBuilder be used?

Always in loops. Even 10+ concatenations. Single concatenation outside loop is fine: str = a + b + c.

Related Claude Code Issues

Can't fix it yourself?
Real developers can help.

You don't need to be technical. Just describe what's wrong and a verified developer will handle the rest.

Get Help