개요
- C# 8부터 지원하는 문자열 보간(String interpolation)과 기존 string.Format 비교
- 자주 사용하는 string 값을 변수에 넣어두면 메모리 관리에 더 효율적일지 확인
코드
StringMem.cs
namespace Study
{
internal class StringMem
{
const string Logformat = "first: {0}, second: {1}, thrid: {2}";
public static void Start(int iterCount)
{
var recorder = new Recorder(true);
recorder.Start("New format");
for (var i = 0; i < iterCount; i++)
{
LogWithFormat(1, 2, 3);
}
recorder.Stop();
recorder.Start("Interpolation");
for (var i = 0; i < iterCount; i++)
{
LogWithFormat(1, 2, 3);
}
recorder.Stop();
recorder.Start("Reuse format");
for (var i = 0; i < iterCount; i++)
{
LogWithFormatVariable(1, 2, 3);
}
recorder.Stop();
}
private static string LogWithFormat(int first, int second, int thrid)
{
return string.Format("first: {0}, second: {1}, thrid: {2}", first, second, thrid);
}
private static string LogWithInterpolation(int first, int second, int thrid)
{
return $"first: {first}, second: {second}, thrid: {thrid}";
}
private static string LogWithFormatVariable(int first, int second, int thrid)
{
return string.Format(Logformat, first, second, thrid);
}
}
}
Recorder.cs
namespace Study
{
internal class Recorder
{
Stopwatch _timer = new Stopwatch();
string _title;
long _bytesPhysicalBefore = 0;
bool _recordMemory;
public Recorder(bool recordMemory = false)
{
_recordMemory = recordMemory;
}
public void Start(string title)
{
_timer.Reset();
_title = title;
if (_recordMemory)
{
var process = Process.GetCurrentProcess();
_bytesPhysicalBefore = process.WorkingSet64;
}
_timer.Start();
}
public void Stop(int testCount = 1)
{
_timer.Stop();
Console.WriteLine($"Title: {_title}");
if (_recordMemory)
{
var process = Process.GetCurrentProcess();
var bytesPhysicalAfter = process.WorkingSet64;
Console.WriteLine($"{bytesPhysicalAfter - _bytesPhysicalBefore} physical bytes used.");
}
Console.WriteLine($"{_timer.ElapsedTicks} total ticks ellapsed.");
Console.WriteLine("--------------------------------------");
}
}
}
Program.cs
StringMem.Start(100000);
출력
# 10회씩 테스트하여 평균냄
Title: New format
8064032 physical bytes used.
185757 total ticks ellapsed.
--------------------------------------
Title: Interpolation
7663616 physical bytes used.
147838 total ticks ellapsed.
--------------------------------------
Title: Reuse format
8015872 physical bytes used.
221520 total ticks ellapsed.
--------------------------------------
결론
- 문자열 보간이 기존 string.Format보다 살짝 메모리, 성능이 좋음
- 문자열 재사용은 효과 없음