Does for loop count elements added into itself during the loop? - c#

My question is, that when I loop through a list with for loop, and add elements to it during this, does it count the elements added while looping?
Simple code example:
for (int i = 0; i < listOfIds.Count(); i++) // Does loop counts the items added below?
{
foreach (var post in this.Collection)
{
if (post.ResponsePostID == listOfIds.ElementAt(i))
{
listOfIds.Add(post.PostId); // I add new item to list in here
}
}
}
I hope my explanation is good enough for you to understand what my question is.

Yes, it usually does. But changing a collection at the same time you're iterating over it can lead to weird behavior and hard-to-find bugs. It isn't recommended at all.

If you want this loop run only for preAdded item count then do this
int nLstCount = listOfIds.Count();
for (int i = 0; i < nLstCount ; i++)
{
foreach (var post in this.Collection)
{
if (post.ResponsePostID == listOfIds.ElementAt(i))
{
listOfIds.Add(post.PostId);
}
}
}

Yes it surely will.The inner foreach loop will execute and add the elements the outer collection and thus will increament the count of the elements.
listOfIds.Count=2 //iteration 1
listOfIds.Add(//element)
when it come to the for loop again
listOfIds.Count=3 //iteration 2

As a slightly abridged explanation of the for loop. You're essentially defining the following:
for (initializer; condition; iterator)
body
Your initializer will will establish your initial conditions, and will only happen once (effectively outside the loop).
Your condition will be evaluated every time to determine whether your loop should run again, or simply exit.
Your iterator defines an action that will occur after each iteration in your loop.
So in your case, your loop will reevaluate listOfIds.Count(); each time, to decide if it should execute; that may or may not be your desired behaviour.
As Dennis points out, you can let yourself get into a bit of a mess (youy loop may run infinitely) if you aren't careful.
A much more detailed/better written explanation can be found on msdn: http://msdn.microsoft.com/en-us/library/ch45axte.aspx

Related

Is using a math class method in a loop condition slow?

if i have a for loop for example and and i want to use something like Math.round() to round the number but i only need to round the number one time(i.e the number doesn't change throughout the loop) is it better to store it into a variable and then use the variable to in the condition or does it not matter?
for (int i = 0;i < Math.Round(x);i++)
{
//Some code
}
vs
for (int i = 0,roundedX = Math.Round(X); i<roundedX;i++)
{
//Some code
}
The compiler will evaluate the termination condition on every loop iteration.
The compiler and the JITter might hoist some expression or part of an expression outside the loop if it deems it is invariant, meaning it doesn't change. This, however, is usually only done with simpler expressions.
If the Math.Round(X) expression could've been done without an actual method call then perhaps but in this particular case the rounding will happen on each loop iteration.
As such, if you're at last line defense for performance problems, you might consider moving this out and into a variable:
int goal = (int)Math.Round(X);
for (int i = 0; i < goal; i++)
...
As this will call the Math.Round method only once, you only get the performance hit once.
Note that if X changes as part of the loop, then obviously you want to keep your original code.
I would suggest defining a variable
var roundedX = Math.Round(X);
for (int i = 0; i < roundedX; i++)
{
//Some code
}

For Loop Expression Syntax Wrong

What is wrong with the following for loop syntax the crv variable is an array and I want an increment of 2:
for(int i<0; i<crv.Count;i+2)
{
//Code Here
}
My compiler only says Semicolon expected which is not a very useful feedback...
You need to start out initializing i to zero, not comparing it to zero. Additionally your last statement doesn't actually change i, it just returns a value of i+2 and does nothing with that value, you need to actually set i to that result.
for(int i = 0; i < crv.Count;i+=2)
{
//Code Here
}
The biggest error is that i+2 is not reassigned to i.
for(int i = 0; i<crv.Count;i = i+2)
{
//Code Here
}
You are throwing away the increment and i never changes value.
Then, you are not initializing i but checking whether it is less than 0.
Please note: first section is assignment You can't use comparison as int i<0;, instead it should be int i=0 or int i = -10 or anything similar as required.
Also in the increment section, either assign the updated value back to i
for(int i =0; i<crv.Count; i+=2)
{
//Code Here
}
or do the same in the body (just mentioning the option, which is useful in some specific scenarios)
for(int i =0; i<crv.Count;)
{
//Code Here
i+=2;
}
While most of these answers do tell you how to fix your code they don't tell you why it doesn't work which I think is important for you to understand.
a for loop consists of three parts, separated by semicolons.
for(part1;part2;part3)
part1 is executed only once - when the execution of the loop first begins. (this is normally where you assign an initial value to your counter)
part2 is then executed next, checking if its value is true or false.
If is true, then the body of the loop is executed
Then part3 is executed, (as you're attempting to do) this is normally where you increment
Then part2 is checked again, if its true, it goes through the process again, if its false it exists the loop
The first part of the for loop decides on i's initial value. in your example, you have "<", which isn't a solid value. Try i=0 instead. also, the last part reads as i, in addition to 2, instead of adding two each iteration. try i+=2 instead.

In .NET, using "foreach" to iterate an instance of IEnumerable<ValueType> will create a copy? So should I prefer to use "for" instead of "foreach"?

In .NET, using "foreach" to iterate an instance of IEnumerable will create a copy? So should I prefer to use "for" instead of "foreach"?
I wrote some code to testify this:
struct ValueTypeWithOneField
{
private Int64 field1;
}
struct ValueTypeWithFiveField
{
private Int64 field1;
private Int64 field2;
private Int64 field3;
private Int64 field4;
private Int64 field5;
}
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("one field");
Test<ValueTypeWithOneField>();
Console.WriteLine("-----------");
Console.WriteLine("Five field");
Test<ValueTypeWithFiveField>();
Console.ReadLine();
}
static void Test<T>()
{
var test = new List<T>();
for (int i = 0; i < 5000000; i++)
{
test.Add(default(T));
}
Stopwatch sw = new Stopwatch();
for (int i = 0; i < 5; i++)
{
sw.Start();
foreach (var item in test)
{
}
sw.Stop();
Console.WriteLine("foreach " + sw.ElapsedMilliseconds);
sw.Restart();
for (int j = 0; j < test.Count; j++)
{
T temp = test[j];
}
sw.Stop();
Console.WriteLine("for " + sw.ElapsedMilliseconds);
sw.Reset();
}
}}
And this is the result that I got after I ran the code:
one field
foreach 68
for 72
foreach 68
for 72
foreach 67
for 72
foreach 64
for 73
foreach 68
for 72
-----------
Five field
foreach 272
for 193
foreach 273
for 191
foreach 272
for 190
foreach 271
for 190
foreach 275
for 188
As we can see in the result, "foreach" always takes more time than "for".
So should I prefer to use "for" instead of "foreach" when iterating through a generic collection of value type?
Note: thanks for the reminder, I edited the code and result. but still, foreach is running slower than for.
Your question is way, way too complex. Break it down.
Does using “foreach” to iterate a sequence of value types create a copy of the sequence?
No.
Does using "foreach" to iterate a sequence of value types create a copy of each value?
Yes.
Does using "for" to do an equivalent iteration of an indexed sequence of value types create a copy of each value?
Usually, yes. There are things you can do to avoid the copying if you know special things about the collection, like for instance that it is an array. But in the general case of indexed collections, indexing the sequence returns a copy of the value in the sequence, not a reference to a storage location containing the value.
Does doing anything to a value type make a copy of the value?
Just about. Value types are copied by value. That's why they're called value types. The only things that you do to value types that do not make a copy are calls to methods on the value type, and passing a value type variable using "out" or "ref". Value types are copied constantly; that's why value types are often slower than reference types.
Does using "foreach" or "for" to iterate a sequence of reference type copy the reference?
Yes. The value of an expression of reference type is a reference. That reference is copied whenever it is used.
So what's the difference between value types and reference types as far as their copying behaviour is concerned?
Value types are copied by value. Reference types copy the reference but not the thing being referred to. A 16-byte value type copies 16 bytes every time you use it. A 16 byte reference type copies the 4 (or 8) byte reference every time you use it.
Is the foreach loop slower than the for loop?
Often it is. The foreach loop is often doing more work, in that it is creating an enumerator and calling methods on the enumerator, instead of just incrementing an integer. Integer increments are extremely fast. Also don't forget that the enumerator in a foreach loop has to be disposed, and that can take time as well.
Should I use the for loop instead of the foreach loop because the for loop is sometimes a few microseconds faster?
No. That's dumb. You should make smart engineering decisions based on customer-focussed empirical data. The extra burden of a foreach loop is tiny. The customer will probably never notice. What you should do is:
Set performance goals based on customer input
Measure to see if you've met your goals
If you have not, find the slowest thing using a profiler
Fix it
Repeat until you've met your goals
Odds are extremely good that if you have a performance problem, changing a foreach loop to a for loop will make no difference whatsoever to your problem. Write the code the way it looks clear and understandable first.
Your test is not accurate; in the foreach version, you're actually spinning up the enumerator and retrieving each value from the list (even though you aren't using it). In the for version, you aren't doing anything with the list at all, other than looking at its Count property. You're essentially testing the performance of an enumerator traversing a collection compared to incrementing an integer variable an equivalent number of times.
To create parity, you'd need to declare a temporary variable and assign it in each iteration of the for loop.
That being said, the answer to your question is yes. A copy of the value will be created with every assignment or return statement.
Performance
This pseudocode breakdown should explain why foreach is somewhat slower than using for in this particular instance:
foreach:
try
{
var en = test.GetEnumerator(); //creates a ListEnumerator
T item;
while(en.MoveNext()) // MoveNext increments the current index and returns
// true if the new index is valid, or false if it's
// beyond the end of the list. If it returns true,
// it retrieves the value at that index and holds it
// in an instance variable
{
item = en.Current; // Current retrieves the value of the current instance
// variable
}
}
finally { }
for:
int index = -1;
T item;
while(++index < test.Count)
{
item = test[index];
}
As you can see, there's simply less code in the for implementation, and foreach has a layer of abstraction (the enumerator) on top of the for. I wrote the for using a while loop to show the two versions in a similar representation.
With all that said...
You're talking about a trivial difference in execution time. Use the loop that makes the code clearer and smaller, and in this circumstance that looks like foreach.
You're not resetting the "stopwatch" after the "for" test, so the time taken in the 'for' test is being added to the subsequent 'foreach' test. Also, as correctly specified, you should do an assignment inside the 'for' to mimic the exact behaviour of the foreach.
sw.Start();
foreach (var item in test)
{
}
sw.Stop();
Console.WriteLine("foreach " + sw.ElapsedMilliseconds);
sw.Restart();
for (int j = 0; j < test.Count; j++)
{
T temp = test[j];
}
sw.Stop();
Console.WriteLine("for " + sw.ElapsedMilliseconds);
sw.Reset(); // -- This bit is missing!
In your for cycle, I don't see you actually accessing items from the test. If you add var x = test[i]; into the for cycle, you'll see that the performance will be (virtually) the same.
Every access to a value-type property creates a copy, either with foreach or using indexer on the list in a for cycle.
here's a discussion on the topic Why should I use foreach instead of for (int i=0; i<length; i++) in loops?
I think that foreach provides an abstract way of looping through but it is technically slower than the for loop, a good article on the differences between the for loop and foreach can be found here
Your test is not fair. Consider how the foreach loop operates. You have the following code:
foreach (var item in test)
{
}
This creates a variable item, and on each iteration fetches the next object from the collection, and assigns it to item. This fetch and assign shouldn't create a copy, but it does take time to access the underlying collection and assign the correct value to the variable.
Then you have this code:
for (int j = 0; j < test.Count; j++)
{
}
This does not access the underlying collection at all. It does not read and assign a variable on each iteration. It simply increments an integer test.Count times, so of course it is faster. And if the compiler is smart, it will see that no operation happens in the loop and just optimize the whole thing away.
A fair comparison would replace that second bit of code with something like:
var item;
for (int j = 0; j < test.Count; j++)
{
item = test.get(j);
}
That is more comparable to what your foreach loop is doing.
As for which to use, it's really a matter of personal preference and coding style. I generally feel that foreach is more clear than for(...) from a readability standpoint.
I found only one case when it matters - Developing for Windows Phone 7. There are two reason why one should change
foreach(var item in colletion)
{
}
To
int length = array.Length;
for(int i = 0; i < length; ++i)
{
}
in XNA game if collections are big or it is called often(f.e. Update method).
It is a bit faster
less garbage
and garbage is critical, since Compact Framework GC fires every 1MB allocation, as a result, it may causes annoying freezes.

Going Through A Foreach When It Can Get Modified? [duplicate]

This question already has answers here:
What is the best way to modify a list in a 'foreach' loop?
(11 answers)
Closed 9 years ago.
I want to do a foreach loop while taking out members of that foreach loop, but that's throwing errors. My only idea is to create another list inside of this loop to find which Slices to remove, and loop through the new list to remove items from Pizza.
foreach(var Slice in Pizza)
{
if(Slice.Flavor == "Sausage")
{
Me.Eat(Slice); //This removes an item from the list: "Pizza"
}
}
You can do this, by far the simplest way I have found (like to think I invented it, sure that's not true though ;))
foreach (var Slice in Pizza.ToArray())
{
if (Slice.Flavor == "Sausage") // each to their own.. would have gone for BBQ
{
Me.Eat(Slice);
}
}
..because it's iterating over a fixed copy of the loop. It will iterate all items, even if they are removed.
Handy isn't it!
(By the way guys, this is a handy way of iterating through a copy of a collection, with thread safety, and removing the time an object is locked: Lock, get the ToArray() copy, release the lock, then iterate)
Hope that helps!
If you have to iterate through a list and need to remove items, iterate backwards using a for loop:
// taken from Preet Sangha's answer and modified
for(int i = Pizza.Count-1; i >= 0, i--)
{
var Slice = Pizza[i];
if(Slice.Flavor == "Sausage")
{
Me.Eat(Slice); //This removes an item from the list: "Pizza"
}
}
The reason to iterate backwards is so that when you remove Elements you don't run into an IndexOutOfRangeException that's caused by accessing Pizza[5] on a Pizza that has only 5 Elements because we removed the sixth one.
The reason to use a for loop is because the iterator variable i has no relation to the Pizza, so you can modify the Pizza without the enumerator "breaking"
use a for loop not a foreach
for(int i = 0; i < in Pizza.Count(), ++i)
{
var Slice = Pizza[i];
if(Slice.Flavor == "Sausage")
{
Me.Eat(Slice); //This removes an item from the list: "Pizza"
}
}
Proably the clearest way to approach this would be to build a list of slices to eat, then to process it, avoiding altering the original enumeration in-loop. I've never been a fan of using indexed loops for this, as it can be error-prone.
List<Slice> slicesToEat=new List<Slice>();
foreach(var Slice in Pizza)
{
if(Slice.Flavor == "Sausage")
{
slicesToEat.Add(Slice);
}
}
foreach(var slice in slicesToEat)
{
Me.Eat(slice);
}
Perhaps change your Me.Eat() signature to take an IEnumerable<Slice>
Me.Eat(Pizza.Where(s=>s.Flavor=="Sausage").ToList());
This lets you perform the task in 1 line of code.
Then your Eat() could be like:
public void Eat(IEnumerable<Slice> remove)
{
foreach (Slice r in remove)
{
Pizza.Remove(r);
}
}
The VB6-styled "Collection" object allows for modification during enumeration, and seems to work sensibly when such modifications occur. Too bad it has other limitations (key type is limited to case-insensitive strings) and doesn't support generics, since none of the other collection types allow modification.
Frankly, I'm not clear why Microsoft's iEnumerable contract requires that an exception be thrown if a collection is modified. I would understand a requirement that an exception be thrown if a changes to a collection would make it impossible for an enumeration to continue without wackiness (skipping or duplicating values that did not change during enumeration, crashing, etc.) but see no reason not to allow a collection that could enumerate sensibly to do so.
Where can you order pizza where slices have separate toppings? Anyway...
Using Linq:
// Was "Me.Eat()" supposed to be "this.Eat()"?
Pizza
.Where(slice => slice.Flavor == "Sausage")
.Foreach(sausageSlice => { Me.Eat(sausageSlice); });
The first two lines create a new list with only sausage slices. The third will take that new subset and pass each slice to Me.Eat(). The { and ;} may be superfluous. This is not the most efficient method because it first makes a copy (as do many other approaches that have been given), but it is certainly clean and readable.
BTW, This is only for posterity as the best answer was already given - iterate backward by index.
What kind of collection is Pizza? If it's a List<T> then you can call the RemoveAll method:
Pizza.RemoveAll(slice => string.Equals(slice.Flavor, "Sausage"));

C# Performance setting value for each list item

I am trying to find the fasted way to set a specific property of every item in a generic list.
Basicly the requirement is to iterate over a list of items and resetting the IsHit property to FALSE. Only the items in a second "hit"-list should be set to TRUE afterwards.
My first attempt looked like this:
listItems.ForEach(delegate(Item i) { i.IsHit = false; });
foreach (int hitIndex in hits)
{
listItems[hitIndex - 1].IsHit = true;
}
Note: hits is 1-based, the items list is 0-based.
Then i tried to improve the speed and came up with this:
for (int i = 0; i < listItems.Count; i++)
{
bool hit = false;
for (int j = 0; j < hits.Count; j++)
{
if (i == hits[j] - 1)
{
hit = true;
hits.RemoveAt(j);
break;
}
}
if (hit)
{
this.listItems[i].IsHit = true;
}
else
{
this.listItems[i].IsHit = false;
}
}
I know this is a micro optimization but it is really time sensitive code, so it would make sense to improve this code beyond readibility... and just for fun of course ;-)
Unfortuanetly I don't really see any way to improve the code further. But I probably missed something.
Thanks
PS: Code in C# / .NET 2.0 would be preferred.
I ended up switching to Eamon Nerbonne solution. But then I noticed something weird in my benchmarks.
The delegate:
listItems.ForEach(delegate(Item i) { i.IsHit = false; });
is faster than:
foreach (Item i in listItems)
{
i.IsHit = false;
}
How is that possible?
I tried to look at IL but thats just way over my head... I only see that the delegates results in fewer lines, whatever that means.
Can you put the items of your second list in a dictionary ?
If so, you can do this:
for( int i = 0; i < firstList.Count; i++ )
{
firstList[i].IsHit = false;
if( secondList.Contains (firstList[i].Id) )
{
secondList.Remove (firstList[i].Id);
firstList[i].IsHit = true;
}
}
Where secondList is a Dictionary offcourse.
By putting the items of your histlist in a Dictionary, you can check with an O(1) operation if an item is contained in that list.
In the code above, I use some kind of unique identifier of an Item as the Key in the dictionary.
A nested for-loop is overkill, and in particular, the "remove" call itself represents yet another for-loop. All in all, your second optimized version has a worse time-complexity than the first solution, in particular when there are many hits.
The fastest solution is likely to be the following:
foreach(var item in listItems)
item.IsHit = false;
foreach (int hitIndex in hits)
listItems[hitIndex - 1].IsHit = true;
This avoids the inefficient nested for-loops, and it avoids the overhead of the delegate based .ForEach method (which is a fine method, but not in performance critical code). It involves setting IsHit slightly more frequently, but most property setters are trivial and thus this is probably not a bottleneck. A quick micro-benchmark serves as a fine sanity check in any case.
Only if IsHit is truly slow, the following will be quicker:
bool[] isHit = new bool[listItems.Count]; //default:false.
//BitArray isHit = new BitArray(listItems.Count);
//BitArray is potentially faster for very large lists.
foreach (int hitIndex in hits)
isHit [hitIndex - 1] = true;
for(int i=0; i < listItems.Count; i++)
listItems[i].IsHit = isHit[i];
Finally, consider using an array rather than a List<>. Arrays are generally faster if you can avoid needing the List<> type's insertion/removal methods.
The var keyword is C# 3.5 but can be used in .NET 2.0 (new language features don't require newer library versions, in general - it's just that they're most useful with those newer libs). Of course, you know the type with which List<> is specialized, and can explicitly specify it.
You could maybe sort the hits collection and perform a binary search, then you would be O(n log2 n) instead of O(n2)

Categories