항복 수익률에 관한 몇 가지 테스트를하고 있는데 정상적인 수익보다 느린 것으로 나타났습니다.'yield return'은 'old school'이 반환하는 것보다 느 립니 까?
필자는 값 변수 (int, double 등)와 일부 참조 유형 (문자열 등)을 테스트했습니다 ... 그리고 두 경우 모두 yield return이 더 느립니다. 왜 그것을 사용 하는가? 내 예를 밖으로
확인 : 하나
public class YieldReturnTeste
{
private static IEnumerable<string> YieldReturnTest(int limite)
{
for (int i = 0; i < limite; i++)
{
yield return i.ToString();
}
}
private static IEnumerable<string> NormalReturnTest(int limite)
{
List<string> listaInteiros = new List<string>();
for (int i = 0; i < limite; i++)
{
listaInteiros.Add(i.ToString());
}
return listaInteiros;
}
public static void executaTeste()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<string> minhaListaYield = YieldReturnTest(2000000).ToList();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds/10);
Console.WriteLine("Yield return: {0}", elapsedTime);
//****
stopWatch = new Stopwatch();
stopWatch.Start();
List<string> minhaListaNormal = NormalReturnTest(2000000).ToList();
stopWatch.Stop();
ts = stopWatch.Elapsed;
elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds/10);
Console.WriteLine("Normal return: {0}", elapsedTime);
}
}
시계 메모리 사용량! List -method는 O (n) 메모리를 사용하는 반면 yield/Enumerator-method는 O (1) 메모리를 소비합니다. 매우 큰 목록의 경우 이는 매우 중요합니다. 또한 임시 목록을 추가하지 않고도 쉽게 열거 형을 연결할 수 있습니다. 이것은 좀 더 일반적인 토론입니다 : http://stackoverflow.com/questions/3628425/ienumerable-vs-list-what-to-use-how-do-they-work –
두 가지 이슈 : 먼저 'NormalReturnTest'가 사전 처리되어야합니다. 그것의리스트 길이를'limite'로 초기화하십시오. 둘째,'.ToList()'메소드가'List'에서 작동 할 때 특별한 검사를 받는다는 사실은 실제로 그 기본 배열을 치고 목록을 반복하고 항목 하나를 복사하는 대신 배열 복사를 수행한다는 것을 확신합니다 하나는 완전히 다른 결과를 낳습니다. 'yield return' 열거 형의'.ToList()'는 모든 요소를 반복하고 배열을 작성해야합니다 (2000000 개 요소를 치기 위해 여러 크기 조정이 필요함). 당신은 잘못된 것을 측정하고 있습니다. –
또 다른 문제는 일반적인 벤치마킹 문제 일뿐입니다. 예를 들어, 단일 실행이 아닌'ToList'의 _many_ 실행을 수행해야합니다. 둘째 시간 차이는 (내 컴퓨터에서) 670ms와 690ms (그리고 크게 변동)입니다. 시간을 변경할 수있는 다른 무관 한 처리 문제가 있기 때문에 너무 많이 읽지는 않습니다. –