주녘공부일지

[C#] StringBuilder VS String 연산 성능 비교 본문

C#/Definition, Etc

[C#] StringBuilder VS String 연산 성능 비교

주녘 2023. 8. 18. 17:40
728x90

1. 성능비교 결과

String += 연산 VS StringBuilder.Insert() VS StringBuilder.Append() 연산

 

 

string은 참조 형식 데이터지만 불변객체이기 때문에 마치 값 형식 데이터처럼 작동함

- 부분 문자열에 대해 추가, 삽입, 삭제할 경우 전체 문자열을 새로 생성해 힙에 할당함

 

StringBuilder 클래스 ( System.Text )는 전체를 새 문자열로 대체하지 않고도 부분문자열에 대해 추가, 삽입, 삭제 연산할 수 있음 ( 최대 용량은 Int.MaxValue )

2. 테스트 코드

        public static void Test()
        {
            int count = 100000;
            string result = "";
            Console.WriteLine($"count : {count}\n");
            Stopwatch stopwatch = new Stopwatch();
            
            // String += 연산
            stopwatch.Start();
            for (int i = 0; i < count; i++)
                result += i.ToString() + " ";
            stopwatch.Stop();

            TimeSpan ts = stopwatch.Elapsed;
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:0000}",
                ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
            Console.WriteLine("String    RunTime : " + elapsedTime);

            stopwatch.Reset();
            StringBuilder sb = new StringBuilder(4096);
            
            // StringBuilder Insert 연산
            stopwatch.Start();
            for (int i = 0; i < count; i++)
            {
                sb.Insert(0, i.ToString());
                sb.Append(" ");
            }
            stopwatch.Stop();
            ts = stopwatch.Elapsed;
            elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:0000}",
                ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
            Console.WriteLine("SB Insert RunTime : " + elapsedTime);

            stopwatch.Reset();
            sb.Clear();
            
            // StringBuilder Append 연산
            stopwatch.Start();
            for (int i = 0; i < count; i++)
            {
                sb.Append(i.ToString());
                sb.Append(" ");
            }
            stopwatch.Stop();
            ts = stopwatch.Elapsed;
            elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:0000}",
                ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
            Console.WriteLine("SB Append RunTime : " + elapsedTime);
        }

 

즉, 문자열 변경이 많다면  StringBuilder를 사용하는 것이 유리함

728x90