Skip to content
created by Aha00aAha00a at 2010-07-27
last modified by Aha00aAha00a at 2016-11-15
revision: 5

C# string VS StringBuilder

Article

string concatenation에 대한 비교.

예전에도 해봤던 거 같은데, 그때는 기록을 안남긴 거 같아서 다음과 같은 루틴으로 비교해 보았다.

    const int iTestCount = 2000000;
    const int iConcatCount = 5;
    using (new CDisposableTrace("string"))
    {
        for (int j = 0; j < iTestCount; j++)
        {
            string s = string.Empty;
            for (int i = 0; i < iConcatCount; i++)
            {
                s = s + i.ToString();
            }
        }
    }

    using (new CDisposableTrace("StringBuilder"))
    {
        for (int j = 0; j < iTestCount; j++)
        {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < iConcatCount; i++)
            {
                stringBuilder.Append(i.ToString());
            }
            string s = stringBuilder.ToString();
        }
    }

1. 결론

  • 더 자세히 하는건 귀찮아서 패스.
  • iConcatCount가 5 이하일 경우 string이 빠르다.
  • iConcatCount가 6 이상일 경우 StringBuilder가 빠르다.
  • 천만번 concat하는데도 몇초 안걸린다. 정말 빨라졌다.
  • 어쨌든 적절히 크기를 예상해서 StringBuilder를 생성할 때 Capacity를 지정해 주는 것은 필수.

-- 2010-07-29

2. See Also

2.2. Similar Pages

Similar pages by cosine similarity. Words after page name are term frequency.

2.3. Adjacent Pages

Control
≤ 32
all
1.0x
1.0x
80
-120
ON
Metrics
Nodes(visible/total)0/0
Links(visible/total)0/0
Avg degree0.00
Depth coverage0
Queue(fetch/graph)0 / 0
Zoom(scale)1.00x
Ctrl/⌘ + Scroll: Zoom
Root 1-hop 2-hop+