Reputation: 41077
I have a huge string as below :
String str = "aaaaaaa"
+ "bbbbbbbb"
+ "cccccccc"
....
+ "zzzzzzzz"; // about 200 lines long
Is it a big waste of memory? Will it be better to put it in one line or use StringBuilder
?
This is done to create a long sql.
Upvotes: 14
Views: 1929
Reputation: 22705
The code:
String str = "aaaaaaa" + "bbbbbbbb" + "cccccccc";
gets transformed at compile time to:
String str = (new StringBuilder()).append("aaaaaaa").append("bbbbbbbb").append("cccccccc").toString();
So, there doesn't appear to be any difference in using StringBuilder.
There's a very nice article that closely compares the performance of concat (+) against StringBuilder and StringBuffer, complete with line graphs:
StringBuilder vs StringBuffer vs String.concat - Done Right.
Upvotes: 1
Reputation: 1303
AFAIK JVM internally has a pool of Strings, every String you create is stored there, discarding the oldest/least used ones (im not sure how it chooses which ones). If you explictly invoke String.intern() youre telling the JVM to put the String in the pool.
when you concatenate two Strings using + you end up with three Strings in the pool. If you concatenate a + b + c, you woyld end up with 5 Strings (a, b, ab, c, abc)
At least thats what i recall on older JVM versions, but Luiggi is quite probably right, that on newer ones its internally optimized
Upvotes: 1
Reputation: 1499760
No. The compiler will perform the concatenation at compile time if all your strings are constant (as they are in your question). So that ends up performing better than the StringBuilder
version.
It will use StringBuilder
(or StringBuffer
) to perform the concatenation of any non-constant parts otherwise.
So the compiled version of:
String x = "a" + "b";
should be exactly the same as:
String x = "ab";
Note that the "non-constant" parts can mean that you can sometimes get (very minor) extra efficiencies using bracketing wisely. For example:
int value = ...;
String x = "a" + value + "b" + "c";
... is less efficient than:
int value = ...;
String x = "a" + value + ("b" + "c");
... as the first appends "b"
and "c"
separately. The efficient version is equivalent tO:
int value = ...;
String x = "a" + value + "bc";
I can't remember ever seeing this used as a legitimate micro-optimization, but it's at least a point of interest.
Upvotes: 25
Reputation: 235984
In current versions of Java, each +
(concatenation) operation gets automatically compiled to a StringBuilder
append()
operation. However, if it's inside a loop, it will create a new StringBuilder
for each iteration, negating its effect - so you'd be better of managing the StringBuilder
explicitly.
Upvotes: 4
Reputation: 5377
No. The compiler will optimise this for you into a StringBuilder
.
Edit: As Louis Wasserman points out, it will also combine String literals for you, so the statement above would just be a single String at compile time.
Upvotes: 2