Avoid String += in Java for Efficient String Manipulation

Today I realized why we should avoid using result+= c in Java. 👉 Every time we use + with String, a new object is created (because Strings are immutable). 👉 This leads to O(n²) time complexity in loops and impacts performance. Instead, we should use StringBuilder / StringBuffer for efficient string manipulation. Here are 🔟 practical string optimization techniques I noted: 🥇 1. Use StringBuilder instead of + ❌ Bad String result = ""; for(char c : arr){ result += c; } ✅ Good StringBuilder sb = new StringBuilder(); for(char c : arr){ sb.append(c); } return sb.toString(); 👉 Reason: Avoids creating new objects repeatedly 🥈 2. Use charAt() instead of toCharArray() (when possible) ❌ char[] arr = str.toCharArray(); ✅ for(int i = 0; i < str.length(); i++){ char c = str.charAt(i); } 👉 Saves extra memory 🥉 3. Use StringBuilder.reverse() ❌ Manual reverse ✅ new StringBuilder(str).reverse().toString(); 🏅 4. Use String.join() String res = String.join(",", a, b, c); 🎯 5. Use .equals() instead of == str1.equals(str2); 👉 == compares reference, not value 🧠 6. Use startsWith() / endsWith() str.startsWith("abc"); ⚡ 7. Use indexOf() for search str.indexOf("abc"); 🔥 8. Avoid split() inside loops String[] parts = str.split(","); 👉 split() uses regex → expensive 🧩 9. Use StringBuilder for insert/delete StringBuilder sb = new StringBuilder(str); sb.insert(i, "x"); 🚀 10. Use String.valueOf() String s = String.valueOf(num); 💡 Key takeaway: If you’re working with strings in loops → always think about immutability + performance #Java #BackendDevelopment #Coding #Performance #DataStructures #SoftwareEngineering

To view or add a comment, sign in

Explore content categories