Recent site activity

C# - C Sharp‎ > ‎Tips and Trick‎ > ‎

StringBuilder optimization in C#

Common mistake for using StringBuilder

A very common msitake that I found a lot of people do when they using StrigBuilder in code is that. Some people use the plus operator on strings within a StringBuilder like following code.
static void Main()
{
    string[] data1 = {"A","B","C","D","E"};
    int[] data2 = {1,2,3,4,5};
    StringBuilder sb = new StringBuilder();
    
    for(int i=0; i<data1.length; i++)
    {
        sb.Append(data1.ToString() + data2);
    }
}

This is kind of bed in it instead of I would like to suggest another way for this situation.
static void Main()
{
string[] data1 = {"A","B","C","D","E"};
int[] data2 = {1,2,3,4,5};
StringBuilder sb = new StringBuilder();

for(int i=0; i<data1.length; i++)
{
sb.Append(data1.ToString()).Append(data2);
}
}