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?
-
Maybe this post could be helpful.0xCursor– 0xCursor2018-10-04 14:14:30 +00:00Commented Oct 4, 2018 at 14:14
-
Related : stackoverflow.com/questions/47605/…alain.janinm– alain.janinm2018-10-04 14:21:42 +00:00Commented Oct 4, 2018 at 14:21
-
Always search Stack Overflow thoroughly before posting.Basil Bourque– Basil Bourque2018-10-04 14:31:50 +00:00Commented Oct 4, 2018 at 14:31
Add a comment
|
1 Answer
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");
}