Freigeben über


DA0001: Use StringBuilder for concatenations

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
Rule Id DA0001
Category .NET Framework Usage
Profiling methods Sampling

Instrumentation
Message Consider using StringBuilder for string concatenations
Message type Warning

Cause

Calls to System.String.Concat are a significant proportion of the profiling data. Consider using the StringBuilder class to construct strings from multiple segments.

Rule description

A String object is immutable. Therefore, any modification to the string creates a new string object and the garbage collection of the original. This behavior is the same whether you call String.Concat explicitly or use the string concatenation operators such as + or +=.. Program performance can decrease if the these methods are frequently called, such as when characters are added to a string in a tight loop.

The StringBuilder class is a mutable object, and, unlike System.String, most of the methods on StringBuilder that modify an instance of this class return a reference to that same instance. You can insert characters or append text to a StringBuilder instance, and remove or replace characters in the instance without the need for allocating a new instance and deleting the original instance.

How to investigate a warning

Double-click the message in the Error List window to navigate to the Function Details View of the sampling profile data. Find the sections of the program that make the most frequent use of string concatenation. Use the StringBuilder class for complex string manipulations, including frequent string concatenation operations.

For more information about how to work with strings, the String Operations section of Chapter 5 - Improving Managed Code Performance in the Microsoft Patterns and Practices library.