-2

Is there any performance difference between these two statements?

IEnumerable<T>.ToList().ForEach(x => Console.WriteLine(x));

and

foreach (var obj in IEnumerable<T>)
   Console.WriteLine(obj)
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172

1 Answers1

4

In the first example, you will

  1. Create a list by enumerating the source
  2. Enumerate through the new list and call Console.WriteLine for each element.

In the second example, you will

  1. Enumerate through the source and call Console.WriteLine for each element.

There are two performance penalities to the first over the second:

  • The creation of the new List object
  • The double enumeration: over the original source, and then the list
Alex
  • 7,639
  • 3
  • 45
  • 58