string , string builder 차이

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace study
{
class Program
{
static void Main(string[] args)
{
string txt = "helloworld ";
StringBuilder sb = new StringBuilder();
sb.Append(txt);
Stopwatch st = new Stopwatch();
st.Start();
for (int i = 0; i < 300000; i++)
{
// txt = txt + "1"; // 느림 // 내 컴퓨터 기준 5초 걸림
sb.Append("1"); // 빠름 // 내 컴퓨터 기준 0초 걸림
}
st.Stop();
Console.WriteLine("second :" + st.ElapsedTicks / 10000 / 1000);
}
}
}



* string : 불변객체 타입이기때문에 string에 대한 모든 변환은 새로운 메모리 할당을 발생 시킴
그래서 + 연산자로 처리하면 메모리를 할당하고 이전 문자열을 다시 복사하는 과정을 반복함

* stringbuilder : 미리 충분한 양의 메모리를 확보한 후 미리 할당한 메모리보다 많아지면 새롭게
여유분의 메모리를 할당함.

그래서 문자열을 연결하는 작업이 많을 때는 반드시 stringBuilder 사용하는 것을 권장.