C#

[담아온글] For vs Foreach Performance 속도 대결

by kay posted Sep 04, 2013
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

결론으로 짧게 정리하면

for문을 사용하고 그 길이를 변수에 저장하고 내부에서 casting 해서 사용하는 것이 foreach 보다 더 빠르다.

경우에 따라 3배정도의 차이가 난다고 합니다....


dataGridView의 출력 속도 때문에 고민하던 중 foreach문에서 느려지는것을 확인하고 찾아본 자료입니다..



처음에는 데브피아에서 자료 (http://www.hoons.net/Board/QACSHAP/Content/33775) 를 찾았는데 돌다보니 아래와 같이 테스트하신 분이 있었네요..


//A comment on a recent post of mine on Stack Overflow suggested that I replace my "for" loop with a more "modern" version using "foreach" and Enumerable.Range. In other words:

// replace this
for (int i = 0; i < 1000; i++)
{
}

// with this
foreach (var i in Enumerable.Range(0, 1000))
{
}
 

//I can't really say that I prefer one over the other, although the second approach does look kinda cool. 
//It'd be even nicer if there were some native support for ranges in C# like there was in Pascal:

// borrowing Pascal's range syntax
foreach (var i in [0..1000])
{
}
//... but I digress. What I wanted to talk about in this post is my findings on the performance difference between a simple "for" loop and a "foreach" over Enumerable.Range.
// I timed two long loops using a Stopwatch:

const int count = 100000000;
var sw = new Stopwatch();

sw.Reset();
sw.Start();
for (int i = 0; i < count; i++)
{
}
sw.Stop();
var forTime = sw.ElapsedTicks;

sw.Reset();
sw.Start();
foreach (var i in Enumerable.Range(0, count))
{
}
sw.Stop();
var foreachTime = sw.ElapsedTicks;

Console.WriteLine(forTime);
Console.WriteLine(foreachTime);
Console.WriteLine((float)foreachTime / forTime);
 
/*
The result:

4869915
14286932
2.933713
So the Enumerable.Range approach is three times slower than a simple for loop.

I guess in a real-world situation where the body of the loop is the thing taking the bulk of the time, there wouldn't be that big a difference, but it's interesting that the two approaches differ in performance by so much. Something to be aware of if you're very performance-oriented in your code, anyway.
*/