Article ID: 306821 - Last Review: December 6, 2006 - Revision: 4.4 How to improve string concatenation performance in Visual Basic .NET or in Visual Basic 2005This article was previously published under Q306821 For a Microsoft Visual C# .NET version of this
article, see
306822
(http://support.microsoft.com/kb/306822/EN-US/
)
. On This PageSUMMARY This article demonstrates the benefits of using the StringBuilder class over traditional concatenation techniques. Strings in the
.NET Framework are invariant (that is, the referenced text is read-only after
the initial allocation). This provides many performance benefits and poses some
challenges to the developer who is accustomed to previous versions of Visual
Basic. One common Visual Basic 6.0 string concatenation technique can be up to
1,000 times faster than the & operator, yet this technique provides no
performance benefits in Visual Basic .NET or Visual Basic 2005. Description of Strings in the .NET FrameworkOne technique to improve string concatenation in Visual Basic 6.0 and earlier was to allocate a large string buffer and use the Mid statement to copy string data into the buffer. This technique is illustrated in the following Microsoft Knowledge Base article:170964
(http://support.microsoft.com/kb/170964/EN-US/
)
How To Improve String Concatenation Performance
In the .NET Framework, a string is immutable; it
cannot be modified in place, unlike strings in earlier versions of Visual
Basic. Instead, any modifications to a string in the .NET Framework cause a new
string to be allocated. Visual Basic .NET still includes a Mid statement, but
its implementation uses concatenation to build the new string as opposed to
modifying the string contents in place. As a result, the technique that is
outlined in
170964
(http://support.microsoft.com/kb/170964/EN-US/
)
does not improve string concatenation
performance in Visual Basic .NET.The .NET Framework includes a StringBuilder class that is optimized for string concatenation. It provides the same benefits as using the Mid statement in previous versions of Visual Basic, as well as automatically growing the buffer size (if needed) and tracking the length for you. The sample application in this article demonstrates the use of the StringBuilder class and compares the performance to concatenation. Build and Run a Demonstration Application
Troubleshooting
REFERENCES The StringBuilder class contains many other methods for in-place string
manipulation that are not described in this article. For more information,
search for "StringBuilder" in the Online Help. | Article Translations
|
Back to the top
