Rethinking Biases: Concatenation and String Builder

Everybody knows that string builder classes are more efficient than concatenation, right? Statements like this are passed between generations of developers, quickly becoming common wisdom. Like all things in technology, rapid language evolution can render dated information irrelevant. So, in the context of Apex development, does this piece of common wisdom hold up? I was recently tasked with a project that required assembling a massive amount of string data into a large JSON payload — it presented the perfect opportunity to put this claim to the test. The answer? Well, it depends, but it was not what I expected. To tightly control as many variables as possible, I created a short code snippet to concatenate two identical strings of a precise size using both techniques. As anticipated, the string builder technique is faster while utilizing few CPU resources with large strings; however, basic concatenation wins in both speed and efficiency when used for smaller tasks.

5,000 Iterations 50,000 Iterations
Concatenation 241 ms 4715 ms
String Builder 445 ms 4614 ms

In fact, concatenation maintains a speed advantage up to a surprisingly high number of iterations. The chart below shows that concatenation holds the lead until just after 55,000 iterations! So, what's the verdict? Basic concatenation is faster under most circumstances. Only extremely large strings benefit from the string builder technique.