stackunderflow
stackunderflow

Reputation: 3873

which is more efficient in conditional looping?

suppose i have the following collection

IEnumerable<car> cars = new IEnumerable<car>();

now I need to loop on this collection.

I need to do some function depending on the car type; so I can do one of the following ways:
Method A:

       foreach( var item in cars){
           if(item.color == white){
              doSomething();
           }
           else{
              doSomeOtherThing();
           }

       }

or the other way:
Method B:

foreach( var item in cars.where(c=>c.color==white)){
   doSomething();
}

foreach( var item in cars.where(c=>c.color!=white)){
  doSomeOtherthing();
}

to me i think method A is better bec. I loop only once on the collection while method B seems enticing bec. the framework will loop and filter the collection for you.

So which method is better and faster ?

Upvotes: 1

Views: 92

Answers (2)

MasterBettor
MasterBettor

Reputation: 109

Method A is more readable than method B. Just one question, is it car.color or item.color?

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881293

Well, it depends on how complicated the filtering process is. It may be so insanely efficient that it's irrelevant, especially in light of the fact that you're no longer having to do your own filtering with the if statement.

I'll say one thing: unless your collections are massive, it probably won't make enough of a difference to care. And, sometimes, it's better to optimise for readabilty rather than speed :-)

But, if you really want to know, you measure! Time the operations in your environment with suitable production-like test data. That's the only way to be certain.

Upvotes: 1

Related Questions