Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for creating objects used in for/foreach loops

Tags:

c#

What's the best practice for dealing with objects in for or foreach loops? Should we create one object outside the loops and recreate it all over again (using new... ) or create new one for every loop iteration?
Example:

foreach(var a in collection) {   SomeClass sc = new SomeClass();   sc.id = a;   sc.Insert(); } 

or

SomeClass sc = null; foreach(var a in collection) {   sc = new SomeClass();   sc.id = a;   sc.Insert(); } 

Which is better?

like image 770
IamDeveloper Avatar asked Mar 15 '10 13:03

IamDeveloper


People also ask

Can you create objects in a loop?

You CAN use a loop. The trick is that you have to save the reference to each one as you create it. A simple way would be to use an array. You have to declare the array outside the loop, then use your loop counter as the index into the array...

What can foreach loops be used for?

The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.

What can't foreach loops be used for?

For-each cannot be used to initialize any array or Collection, because it loops over the current contents of the array or Collection, giving you each value one at a time.

Which is faster for loop or foreach?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


1 Answers

The first way is better as it more clearly conveys the intended scope of the variable and prevents errors from accidentally using an object outside of the intended scope.

One reason for wanting to use the second form is if you want to break out of the loop and still have a reference to the object you last reached in the loop.

A bad reason for choosing the second form is performance. It might seem at first glance that the second method uses fewer resources or that you are only creating one object and reusing it. This isn't the case here. The repeated declaration of a variable inside a loop doesn't consume any extra resources or clock cycles so you don't gain any performance benefit from pulling the declaration outside the loop.

like image 79
Mark Byers Avatar answered Sep 27 '22 19:09

Mark Byers