2

What is the fastest way to set properties (any one) to null in an IEnumerable? Is foreach my only option?

Spontifixus
  • 6,570
  • 9
  • 45
  • 63
Greens
  • 3,061
  • 11
  • 43
  • 61

2 Answers2

7

If you have a very large list, you could consider doing this in parallel:

enumerable.AsParallel().ForAll(a => a.Value = null);

But worth benchmarking and baring in mind that your objects will now need to be threadsafe.

Quick tests here showed a return on investment when the list size was above 10 million items*. Lower list sizes and the costs of setting up the parallel processing outweighs the benefits.

*Your Mileage Will Vary

weston
  • 54,145
  • 21
  • 145
  • 203
  • 1
    Of course the empirical 10 million limit may depend very much on the hardware architecture used (and on what else is going on on that machine). – Jeppe Stig Nielsen Jan 28 '13 at 16:02
1

There are two ways of achieving your goal:

  1. As you mentioned:

    foreach(var item in enumeration)
    {
        item.Property = null;
    }
    
  2. You can go with LINQ also:

    enumeration.ToList().ForEach(item => item.Property = null);
    

While the second way looks a shorter and better readable, it may execute slower, because as Jeppe Stig Nielsen pointed out, the IEnumerable gets converted into a List (be enumerating it the first time) and that list gets enumerated again, to finally set the property.

Thus you are right: foreach is your only option. However the foreach-representation will look like, you always will need to iterate over the collection to modify each item.

Spontifixus
  • 6,570
  • 9
  • 45
  • 63
  • 3
    Your option 2 is uglier and slower. It first creates a new `List<>` object and iterates through `enumeration` (the LINQ extension). Then it iteratates through the new `List<>` object (the `ForEach` instance method on `List<>`). So two iterations instead of one, a lot of values (references) are copied in the first iteration, so more memory is used. The `List<>` instance is not kept and will be garbage collected. – Jeppe Stig Nielsen Jan 28 '13 at 15:35
  • @JeppeStigNielsen thanks for pointing that out. I adopted my answer accordingly. – Spontifixus Jan 28 '13 at 15:46