This product is not supported for your selected Datadog site. ().
이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다.
현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.

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.

Non-Compliant Code Examples

using System.Collections.Generic;

public class MyController
{
    public string DoSomething(List<Stuff> listOfStuff)
    {
        string html = "";

        for (int i = 0; i < listOfStuff.Count; i++)
        {
            var stuff = listOfStuff[i];
            html += "<div class='product'><h3>" + stuff.Name + "</h3><p>" + stuff.Description + "</p></div>";
            html = html + "<div class='product'><h3>" + stuff.Name + "</h3><p>" + stuff.Description + "</p></div>";
        }

        return html;
    }
}

public class Stuff
{
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
}
public class MyController {
    
    public void DoSomething(Iterable listOfStuff) {
        foreach (var stuff in listOfStuff)
        {
            html += $@"
                <div class='product'>
                    <h3>{stuff.Name}</h3>
                    <p>{stuff.Description}</p>
                    <p>Price: ${stuff.Price}</p>
                </div>";
        }
    }
}
using System.Collections.Generic;

public class MyController
{
    public string DoSomething(List<Stuff> listOfStuff)
    {
        string html = "";

        for (int i = 0; i < listOfStuff.Count; i++)
        {
            var stuff = listOfStuff[i];
            html += $@"
                <div class='product'>
                    <h3>{stuff.Name}</h3>
                    <p>{stuff.Description}</p>
                    <p>Price: ${stuff.Price}</p>
                </div>";
        }

        return html;
    }
}

public class Stuff
{
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
}

Compliant Code Examples

using System.Text;
using System.Collections.Generic;

public class MyController
{
    public string DoSomething(IEnumerable<Stuff> listOfStuff)
    {
        var htmlBuilder = new StringBuilder();

        foreach (var stuff in listOfStuff)
        {
            htmlBuilder.AppendLine($@"
                <div class='product'>
                    <h3>{stuff.Name}</h3>
                    <p>{stuff.Description}</p>
                    <p>Price: ${stuff.Price}</p>
                </div>");
        }

        return htmlBuilder.ToString();
    }
}

public class Stuff
{
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

원활한 통합. Datadog Code Security를 경험해 보세요