THE STRINGBUILDER CLASS
The & and &= operators are useful for concatenating a few strings together. However, if you must combine a large number of strings, you may get better performance by using the StringBuilder class. This class is optimized for performing long sequences of concatenations to build big strings.
For small pieces of code, the difference between using a String and a StringBuilder is negligible. If you need to concatenate a dozen or so strings once, using a StringBuilder won’t make much difference in run time and may even slow performance slightly.
However, if you make huge strings built up in pieces, or if you build simpler strings but many times in a loop, StringBuilder may make your program run faster.
Example program StringBuilderTest1, which is available for download on the book’s website, concatenates the string 1234567890 a large number of times, first using a String variable and then using a StringBuilder. In one test that performed the concatenation 10,000 times to build strings 100,000 characters long, using a String took roughly 1.6 seconds. Using a StringBuilder, the program was able to build the string in roughly 0.001 seconds.
Admittedly, building such enormous strings is not a common programming task. Even when the strings are shorter, you can sometimes see a noticeable difference in performance, particularly if you must build a large number of such strings.
Example program StringBuilderTest2, which is also available for download, concatenates the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access