47 lines
1.2 KiB
Plaintext
47 lines
1.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Strings are immutable objects, so concatenation doesn't simply add the new String to the end of the existing string. Instead, in each loop iteration, the first String is converted to an intermediate object type, the second string is appended, and then the intermediate object is converted back to a String. Further, performance of these intermediate operations degrades as the String gets longer. Therefore, the use of StringBuilder is preferred.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
String str = "";
|
|
for (int i = 0; i < arrayOfStrings.length ; ++i) {
|
|
str = str + arrayOfStrings[i];
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
StringBuilder bld = new StringBuilder();
|
|
for (int i = 0; i < arrayOfStrings.length; ++i) {
|
|
bld.append(arrayOfStrings[i]);
|
|
}
|
|
String str = bld.toString();
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 21 Nov 2024, 16:48:00 Alban Auzeill wrote:
|
|
[test-code-support-investigation-for-java] Decision for scope: Main -> All.
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|