Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between following two statements?

We can count process by the following statement

var query = Process.GetProcesses()
             .Where(m => m.ProcessName.StartsWith("S")).Count();

But ReShaper suggests me like following statement

var query = Process.GetProcesses().Count(m => m.ProcessName.StartsWith("S"));

My question is ... Which one is better if I consider performance issue???

like image 512
Atish Dipongkor Avatar asked Dec 30 '25 17:12

Atish Dipongkor


1 Answers

First statement will create WhereIterator internally, which will iterate over source and apply predicate. Count calculation will look like:

var iterator = new WhereArrayIterator<TSource>((TSource[]) source, predicate);

int num = 0;

using (IEnumerator<TSource> enumerator = iterator.GetEnumerator())
{
   while (enumerator.MoveNext())
       num++;      
}

return num;

But second statement will not create iterator - it will apply predicate while iterating directly over source sequence:

int num = 0;

foreach (TSource local in source)
{
    if (predicate(local))        
        num++;        
}

return num;

So, second statement has slightly better performance.

like image 56
Sergey Berezovskiy Avatar answered Jan 02 '26 09:01

Sergey Berezovskiy



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!