250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- Ainimation Blending
- Transform
- Hpbar
- Parallax
- CSharp #자료구조
- Prefabs
- 프리팹
- 유니티
- raycasting
- raycast
- rigidbody
- rotation
- Object Pooling
- 오브젝트 풀링
- Object Poling
- Blend Type
- apk
- Hp바
- Vector3
- LayerMark
- Scrooling
- 플레이어 방향전환
- 패럴렉스
- Unity
- joystick
- 일시정지
- 2D슈팅게임
- 스크롤링
- 플레이어 이동
- Animation State Machine
Archives
- Today
- Total
주녘공부일지
[C#] StringBuilder VS String 연산 성능 비교 본문
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
'C# > Definition, Etc' 카테고리의 다른 글
[C#] 인터페이스 ( interface ) (0) | 2023.10.12 |
---|---|
[C#] Object 형식과 박싱&언박싱 (0) | 2023.10.11 |
[C#] 스택 메모리 & 힙 메모리 (0) | 2023.10.04 |
[C#] 값 형식과 참조 형식 ( + 제네릭 형식, 포인터 형식 ) (0) | 2023.09.29 |
[C#] 자료구조 ( 제네릭 컬렉션 ) (0) | 2023.03.09 |