[C#] for(), foreach() 문에 대한 고찰

0시0분·2024년 2월 5일
0

C#

목록 보기
5/9

일반적으로 구글링을 했을때나, 챗GPT에게 물어봤을 때
두 반복문의 성능 차이가 크지 않기 때문에
더 간결하고 가독성이 좋은 foreach 문을 사용할 것을 추천하는 경우가 많았다.

그러다 이 블로그 글을 발견했다.

'foreach() 문 + var 형'의 조합이 가장 느리다는 내용이었는데,
마침 진행중인 프로젝트의 코드가 해당 조합을 많이 사용중이어서 바로 테스트를 진행해봤다.

반복문 횟수 10000일 때

List<int> testlist = new List<int>();
for (int i = 0; i < 10000; ++i)
    testlist.Add(i);
Stopwatch stopwatch = new Stopwatch();

stopwatch.Start();
for (int i = 0; i < testlist.Count; ++i)
{
    Debug.Log(i);
}
stopwatch.Stop();
Debug.Log($"@@ For문 : {stopwatch.ElapsedMilliseconds}ms");

stopwatch.Reset();
stopwatch.Start();
for (var i = 0; i < testlist.Count; ++i)
{
    Debug.Log(i);
}
stopwatch.Stop();
Debug.Log($"@@ For + var 문 : {stopwatch.ElapsedMilliseconds}ms");

stopwatch.Reset();
stopwatch.Start();
foreach (int i in testlist)
{
    Debug.Log(i);
}
stopwatch.Stop();
Debug.Log($"@@ Foreach 문 : {stopwatch.ElapsedMilliseconds}ms");

stopwatch.Reset();
stopwatch.Start();
foreach (var i in testlist)
{
    Debug.Log(i);
}
stopwatch.Stop();
Debug.Log($"@@ Foreach + var 문 : {stopwatch.ElapsedMilliseconds}ms");

(Stopwatch 클래스를 처음 써봤다. 간편해서 좋은 것 같다.)

결과는 그냥저냥 비슷했다.
오히려 foreach() + var형의 조합이 for문 단일 사용일 때 보다 더 빠른 결과가 나왔다.

반복문 횟수 5000일 때

반복문 횟수 15000일 때


반복 횟수가 늘어나니까 확실하게 격차가 벌어졌다.
for문이 가장 빠르고, foreach() + var의 조합이 가장 느렸다. 0.7초 가량 차이가 난다.

그러나 많은 양을 처리하는게 아니라면 성능에 크게 영향은 없을것 같다.

0개의 댓글