-1

The question is simple, what is better for avoiding of non-appropriated memory using? For example, let's say that we've a String s = "Test" and we'd like to add 1 to it so it becomes Test1. We all know that s gets a memory location and if we use StringBuilder, Test1 will get a new memory address or it'll remain at s's place, and what if we use concat?

Anthino Russo
  • 59
  • 1
  • 8

1 Answers1

5

One line concatenations are optimized and converted to StringBuilder under the hood. Memory wise is the same thing, but the manual concatenation is more concise.

// the two declarations are basically the same
// JVM will optimize this to StringBuilder
String test = "test";
test += "test";

StringBuilder test = new StringBuilder();
test.append("test");

On the other hand, if you don't do trivial concatenations, you will be better off with StringBuilder.

// this is worse, JVM won't be able to optimize
String test = "";
for(int i = 0; i < 100; i ++) {
    test += "test"; 
} 

// this is better
StringBuilder builder = new StringBuilder();
for(int i = 0; i < 100; i ++) {
    builder.append("test"); 
}