Java/Spring Boot Performance Tip: Use StringBuilder for Loops

💡 𝗝𝗮𝘃𝗮/𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 𝐏𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞 𝐓𝐢𝐩 🔥 💎 𝗣𝗿𝗲𝗳𝗲𝗿 𝗦𝘁𝗿𝗶𝗻𝗴𝗕𝘂𝗶𝗹𝗱𝗲𝗿 𝗢𝘃𝗲𝗿 𝗦𝘁𝗿𝗶𝗻𝗴 𝗖𝗼𝗻𝗰𝗮𝘁𝗲𝗻𝗮𝘁𝗶𝗼𝗻 𝗶𝗻 𝗟𝗼𝗼𝗽𝘀 🐌 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝘄𝗶𝘁𝗵 𝗦𝘁𝗿𝗶𝗻𝗴 𝗖𝗼𝗻𝗰𝗮𝘁𝗲𝗻𝗮𝘁𝗶𝗼𝗻  Strings are immutable in Java, so the '+' operator creates a new String object with every concatenation. In loops, this creates thousands of temporary objects that need to be garbage collected. This dramatically impacts both performance and memory usage. 🔥 𝗪𝗵𝘆 𝗦𝘁𝗿𝗶𝗻𝗴𝗕𝘂𝗶𝗹𝗱𝗲𝗿 𝗶𝘀 𝗕𝗲𝘁𝘁𝗲𝗿 StringBuilder uses a mutable character buffer and modifies it in place without creating new objects. In benchmarks with 10,000 iterations, StringBuilder completes in ~4ms while '+' operator takes ~400ms. That's 100x faster with significantly lower memory allocation. ✅ 𝗪𝗵𝗲𝗻 𝘁𝗼 𝗨𝘀𝗲 𝗘𝗮𝗰𝗵 ◾ Use StringBuilder for loops and multiple concatenations. ◾ Use '+' for simple, single-line string building (2-3 strings). ◾ The compiler optimizes simple '+' usage, but not in loops. #java #springboot #programming #softwareengineering #softwaredevelopment

  • text

Clean explanation and very practical advice.

🏠 Andriy Bezkorovayny

Senior Software Engineer @ DHL IT Services | .NET | Software Design & Implementation

2mo

SERKUT YILDIRIM, Nice tip! We can improve this further by avoiding substring(), which creates temporary String objects. Instead of sb.append(name.substring(0, 4));, use sb.append(name, 0, 4);.

Like
Reply

I love it inside c# too and instead of substring we can use .AsSpan().

Like
Reply

Great reminder. Small optimizations like using StringBuilder in loops make a big difference in performance at scale.

Like
Reply

name.Substring is old approach with bad performance, instead it's need to use Span collection

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories