c# 문자열 “”와 string.Empty의 성능 차이
문자열 “”과 string.Empty는 널이 아니고 아무 문자도 담겨 있지 않은 상태로 서로 같다. 그러나 처리 과정은 다르다. “”은 객체가 만들어진다. 그렇다면 그 과정 때문에 처리가 더 늦을까? 두 개의 방법으로 성능을 비교해 봤지만 특별한 차이가 없거나 오히려 “”가 더 빨랐다.
변수 값 쓰기
아래의 예제는 문자열 변수에 “”와 string.Empty를 각각 쓰는 거다. 워밍-업 결과를 뺀 안정된 다섯 번의 평균은 각각 18,434와 18,014로 “”가 더 느렸다. 그러나 그 차이가 특별한 정도는 아니다.
string String;
private void button1_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = new();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
{
String = "";
}
textBox1.AppendText(stopwatch.ElapsedTicks.ToString() + "\r\n");
}
private void button2_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = new();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
{
String = string.Empty;
}
textBox2.AppendText(stopwatch.ElapsedTicks.ToString() + "\r\n");
}
조건문의 비교 대상
아래의 예제는 조건문의 비교 대상으로 쓰는 거다. 위와 같은 방법으로 해 보니 결과는 각각 18,016과 19,301로 string.Empty가 더 느렸다.
private void button3_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = new();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
{
if (String == "")
{
}
}
textBox1.AppendText(stopwatch.ElapsedTicks.ToString() + "\r\n");
}
private void button4_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = new();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
{
if (String == string.Empty)
{
}
}
textBox2.AppendText(stopwatch.ElapsedTicks.ToString() + "\r\n");
}
복잡하게 생각할 거 없이 그냥 “”을 쓰면 된다.