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
?
Asked
Active
Viewed 6,841 times
-1

Anthino Russo
- 59
- 1
- 8
-
Maybe [this post](https://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java) could be helpful. – 0xCursor Oct 04 '18 at 14:14
-
Related : https://stackoverflow.com/questions/47605/string-concatenation-concat-vs-operator – alain.janinm Oct 04 '18 at 14:21
-
Always search Stack Overflow thoroughly before posting. – Basil Bourque Oct 04 '18 at 14:31
1 Answers
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");
}
-
[for the record, some real numbers](https://stackoverflow.com/a/49466784/1059372) – Eugene Oct 05 '18 at 09:39