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.
Java - String concat() Method This method appends one String to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.
In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.
You can only pass a String to the concat() method. If one of the operands is a string and another is a non-string value. The non-string value is internally converted to a string before concatenation.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With