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 string 1234567890 to itself 100 times, making a string 1,000 characters long. It builds the string repeatedly for a certain number of trials. In one test building the 1,000-character string 10,000 times, using a String took around 0.95 seconds but using a StringBuilder took only about 0.06 seconds.

Strings and string operations are a bit more intuitive than the StringBuilder class, so your code will usually be easier to read if you use String variables when performance isn’t a big issue. If you are building enormous strings, or are building long strings a huge number of times, the performance edge given by the StringBuilder class may be worth slightly more complicated-looking code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.83.182