This product is not supported for your selected Datadog site. ().
Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
Metadata
ID:csharp-best-practices/use-stringbuilder
Language: C#
Severity: Info
Category: Best Practices
Description
This rule encourages the use of StringBuilder when constructing strings inside loops instead of using string concatenation. Using + or += to concatenate strings in a loop creates multiple intermediate string instances, which can lead to significant performance overhead due to repeated memory allocation and copying.
Avoiding this pattern is important because strings in C# are immutable, so each concatenation generates a new string object. This can increase memory usage and degrade performance, especially when building large strings or iterating over many elements.
To comply with this rule, use a StringBuilder instance to accumulate string content within loops. For example, instantiate a StringBuilder before the loop, call Append or AppendLine inside the loop to add content, and finally convert it to a string with ToString() after the loop completes.
By following this approach, you write more efficient, readable, and maintainable code that scales better when dealing with dynamic string construction in iterative contexts.