Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficent way to work with IEnumerable

What is the most efficient way to traverse a collection/IEnumeration in C#. I have a list which contains almost 1100 objects. almost 10 of those objects, inturn contain 1000 subobjects (of same type). Traversal to this list takes almost 5-6 seconds. Here is my code:

foreach (Parameter par in this.AllParameters) //this.AllParameters is Generic.List type
{
    foreach (Parameter subPar in par.WrappedSubParameters)
    {
        subPar.IsSelected = false;
    }
    par.IsSelected = false;
}

Is there a way to optimize this code so that it is fast enough, not taking 5-6 seconds?

like image 437
Irfan Avatar asked Dec 31 '25 17:12

Irfan


2 Answers

The loops, as written, are likely one of the fastest options.

Since this is all in memory, and each write operation appears to be on a separate instance (no synchronization), you could potentially parallelize this to get some gains:

Parallel.ForEach(this.AllParameters, par =>
{
    foreach (Parameter subPar in par.WrappedSubParameters)
    {
        subPar.IsSelected = false;
    }
    par.IsSelected = false;
});

Note that I'm only parallelizing the outer loop (on purpose), as this should provide enough work items to adequately use all processing cores.


Another potential issue - if your IsSelected properties are bound to a control via Data binding, your UI will potentially be updating continually, which could explain the very slow update times. This would cause parallelization to have no real effect, as well, since the bottle neck would not be these loops, but rather the UI binding.

You may want to unbind/rebind the control, or suspend updates on the control until you're loop is completed.

like image 51
Reed Copsey Avatar answered Jan 02 '26 09:01

Reed Copsey


The loop you have written is already the most efficient way to iterate. The only problem could be binding to User Interface elements (Grid, List, etc).

One workaround in MVVM is that unbind the databindings and after you are done itrating, bind them again.

Otherwise, do not set the actual properties, just set the fields, and after iteration you can notify the userinterface.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!