Is yield return fast? Or does it incur a significant performance loss? Yield return does have some overhead, but if you need its advanced features it can be faster.
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
const int _max = 1000000;
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
var s1 = Stopwatch.StartNew();
// Version 1: use foreach with array.
for (int i = 0; i < _max; i++)
{
if (Method1(numbers) != 300)
{
throw new Exception();
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use foreach with yield keyword.
for (int i = 0; i < _max; i++)
{
if (Method2(numbers) != 300)
{
throw new Exception();
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
static int Method1(int[] numbers)
{
// Sum with simple statements.
int sum = 0;
foreach (int number in numbers)
{
sum += number * 2;
}
return sum;
}
static int Method2(int[] numbers)
{
// Use yield return to get multiplied numbers and then sum those.
int sum = 0;
foreach (int number in GetNumbers(numbers))
{
sum += number;
}
return sum;
}
static IEnumerable<int> GetNumbers(int[] numbers)
{
// Return all numbers multiplied.
foreach (int number in numbers)
{
yield return number * 2;
}
}
}
3.84 ns inline expression
50.68 ns yield return