C# While Loop vs For Loop? - c#

In C# a question has been bugging me for a while and its what is that actual major difference between a While and For Loop. Is it just purely readability ie; everything you can essentially do in a for loop can be done in a while loop , just in different places. So take these examples:
int num = 3;
while (num < 10)
{
Console.WriteLine(num);
num++;
}
vs
for (int x = 3; x < 10; x++)
{
Console.WriteLine(x);
}
Both code loops produce the same outcome and is the only difference between the two that the for loop forces you to declare a new variable and also set the iteration value each loop cycle at the start? Maybe I'm missing something else in terms of any major differences but it would good if someone can set me straight regarding this. Thanks.

is the only difference between the two that the for loop forces you to declare a new variable and also set the iteration value each loop cycle at the start?
The for loop forces you to nothing. You can omit any of the 3 elements. The smallest form is
for(;;) // forever
{
DoSomething();
}
But you can use the 3 elements to write more concise code:
for(initializer; loop-condition; update-expression)
{
controlled-statements;
}
is equivalent to:
{
initializer;
while(loop-condition)
{
controlled-statements;
continue_target: // goto here to emulate continue
update-expression;
}
}
Note the outer {} braces, in for(int i = 0; ...; ...) the i is local to the for-loop. A clear benefit.
But the major difference in usage is when you call continue; inside the loop, much easier to get the logic wrong in a while-loop than in a for-loop.

Yes, they're exactly the same in the background (in Assembly, that is).
Usually, it is more common to use the for loop when the number of repeats is known and we're not going to change our counter(index).
while loop also has the advantage of a sentinel loop which is easier for example when taking inputs from a user until something specific is given.

Fundamentally, the differences are:
For loop knows in advance how many times it will loop, whereas a while loop doesn’t know.
For loop has an initialization step whereas a while loop doesn’t
For loop uses a “step value” or increment/decrement step, whereas a while loop doesn’t.
Here is an example of a Java for loop looping from 0 to 99 and printing out the numbers. Notice how the loop is initialized and incremented as part of the for loop structure.
for(int i=0; i<100; i++) {
System.out.println(i);
}
Here is an example of a Java while loop printing out all the elements in an integer array. Notice how the loop variable is initialized before the loop and is incremented inside the loop body.
int [] intArray = {1, 3, 5, 7, 9};
int i=0;
while(i<intArray.length) {
System.out.println(intArray[i++]);
}

When you are sure what will be the end value or how much the loop should execute(until what value), use 'for' loop, otherwise use 'while' loop.

Related

While Looping an Array

I'm trying to understand a book from Don Gosselin on ASP.NET Programming with Visual C#. To solve it I just simply make it to work by adhering to while loops: one while loop is to assign a number to an array element, the other while loop is to display that array. Total array count displays 1 through 100. This should have worked but didn't. Visual Studio 2013 debugger for some reason assigns count = 100, that's why it's failing.
<%
int count = 0;
int[] numbers = new int[100];
while (count <= 100)
{
numbers[count] = count;
++count;
}
while (count <= 100)
{
Response.Write(numbers[count] + "<br />");
++count;
}
%>
You should set count to 0 after first while loop:
int count = 0;
int[] numbers = new int[100];
while (count <= 100)
{
numbers[count] = count;
++count;
}
count = 0;
while (count <= 100)
{
Response.Write(numbers[count] + "<br />");
++count;
}
You need to reset the count to 0 before you attempt the next while statement. Currently, the first loop ends when it reaches a count equal to 101. WHen you proceed to the next while, the count is 101 so the loop automatically ends. Just set count = 0; before the second while loop.
This seems like a very convoluted and unrealistic way of using while loops and arrays. In order to understand it better, it may be worth thinking about it per step.
var i = 0;
while (i < 100)
{
Response.Write(++i + "<br />");
}
The first important distinction is between i++ and ++i. The former utilises the value, and then increments by one; the latter, increments the number and then utilises the value.
In C#, you should really be working with Collections, rather than Arrays. Arrays are zero-indexed, and are renowned for causing serious errors, including exposing potential exploits. Being statically allocated, there is no failsafe when attempting to access indicies outside of the bounds of the Array. Collections, on the other hand, are (for the most part) one-indexed, dynamically allocated, and provide fallbacks when accessing indicies. The most commonly used Collection is a List.
var i = 1;
var list = new List<int>();
while (i <= 100)
{
list.Add(i++);
}
For the second while loop, it's not really suitable to use a while loop here, for any practical example. The excercise is forcing while loops where they are not needed. In this instance, the aim is to iterate through each element in the array (List) and dump its contents to the screen. Because we want to perform an action for each element, a while loop may cause issues. If the array has less than 100 elements, the program will crash, if the array has more than 100 elements, we'll miss some of them. By using a foreach loop, instead of a while, we can eliminate these potential errors.
foreach (var num in list)
{
Response.Write(num + "<br />");
}
Now, I realise that the excercise is about while loops, however, it is teaching you to use them in the wrong way. A much better way - and how you'll most often use them - is to perform an action until a particular condition is met, rather than for simple iteration. By this, I mean, a condition is set to false, then inside the while loop, we manipulate a variable, test the condition, and if it's still false, we go round again. The most common example of this is to work out factorials of numbers.
var num = 5;
var factorial = 1;
while (counter > 1)
{
factorial *= num--;
}
Response.Write(String.Format("{0}! = {1}", input, factorial));
The other main way in which while loops are used is to force an infinite loop, unless a break condition is met. I'll show a very arbitrary use of this here, but a real world example would be the loop() method in Arduino C coding, or a HTTP Listener that constantly repeats the same procedures, until stopped.
var stop = 13;
Response.Write("Pick a number between 1 and 100...<br /><br />");
while (true)
{
var num = new Random().Next(1, 101);
Response.Write(num + " ..... ");
if (num == stop) break;
Response.Write("You got lucky!<br />");
}
Response.Write("Unlucky for you!);
The best way to learn these things is to practice them. Pick a task and find out just how many ways there are to complete it. There is one last important distinction to mention though. a while loop tests the condition at the beginning of the loop. A do while loop, tests the condition at the end.
while(false)
{
// This code will never be run.
}
Compared to:
do
{
// This code will be run once only.
}
while(false)
As a final thought, here's how I'd write the original code (using a LINQ foreach loop):
var numbers = new List<int>();
for (var count = 1; count <= 100; count++)
{
numbers.Add(count);
}
numbers.ForEach(num => Response.Write(num + "<br />")));

What is the difference between for and foreach?

What is the major difference between for and foreach loops?
In which scenarios can we use for and not foreach and vice versa.
Would it be possible to show with a simple program?
Both seem the same to me. I can't differentiate them.
a for loop is a construct that says "perform this operation n. times".
a foreach loop is a construct that says "perform this operation against each value/object in this IEnumerable"
You can use foreach if the object you want to iterate over implements the IEnumerable interface. You need to use for if you can access the object only by index.
I'll tryto answer this in a more general approach:
foreach is used to iterate over each element of a given set or list (anything implementing IEnumerable) in a predefined manner. You can't influence the exact order (other than skipping entries or canceling the whole loop), as that's determined by the container.
foreach (String line in document) { // iterate through all elements of "document" as String objects
Console.Write(line); // print the line
}
for is just another way to write a loop that has code executed before entering the loop and once after every iteration. It's usually used to loop through code a given number of times. Contrary to foreach here you're able to influence the current position.
for (int i = 0, j = 0; i < 100 && j < 10; ++i) { // set i and j to 0, then loop as long as i is less than 100 or j is less than 10 and increase i after each iteration
if (i % 8 == 0) { // skip all numbers that can be divided by 8 and count them in j
++j
continue;
}
Console.Write(i);
}
Console.Write(j);
If possible and applicable, always use foreach rather than for (assuming there's some array index). Depending on internal data organisation, foreach can be a lot faster than using for with an index (esp. when using linked lists).
Everybody gave you the right answer with regard to foreach, i.e. it's a way to loop through the elements of something implementing IEnumerable.
On the other side, for is much more flexible than what is shown in the other answers. In fact, for is used to executes a block of statements for as long as a specified condition is true.
From Microsoft documentation:
for (initialization; test; increment)
statement
initialization
Required. An expression. This expression is executed only once, before the loop is executed.
test
Required. A Boolean expression. If test is true, statement is executed. If test if false, the loop is terminated.
increment
Required. An expression. The increment expression is executed at the end of every pass through the loop.
statement
Optional. Statement to be executed if test is true. Can be a compound statement.
This means that you can use it in many different ways. Classic school examples are the sum of the numbers from 1 to 10:
int sum = 0;
for (int i = 0; i <= 10; i++)
sum = sum + i;
But you can use it to sum the numbers in an Array, too:
int[] anArr = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
int sum = 0;
for (int i = 0; i < anArr.Length; i++)
sum = sum + anArr[i];
(this could have been done with a foreach, too):
int[] anArr = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
int sum = 0;
foreach (int anInt in anArr)
sum = sum + anInt;
But you can use it for the sum of the even numbers from 1 to 10:
int sum = 0;
for (int i = 0; i <= 10; i = i + 2)
sum = sum + i;
And you can even invent some crazy thing like this one:
int i = 65;
for (string s = string.Empty; s != "ABC"; s = s + Convert.ToChar(i++).ToString()) ;
Console.WriteLine(s);
for loop:
1) need to specify the loop bounds( minimum or maximum).
2) executes a statement or a block of statements repeatedly
until a specified expression evaluates to false.
Ex1:-
int K = 0;
for (int x = 1; x <= 9; x++){
k = k + x ;
}
foreach statement:
1)do not need to specify the loop bounds minimum or maximum.
2)repeats a group of embedded statements for
a)each element in an array
or b) an object collection.
Ex2:-
int k = 0;
int[] tempArr = new int[] { 0, 2, 3, 8, 17 };
foreach (int i in tempArr){
k = k + i ;
}
foreach is almost equivalent to :
var enumerator = list.GetEnumerator();
var element;
while(enumerator.MoveNext()){
element = enumerator.Current;
}
and in order to implemetn a "foreach" compliant pattern, this need to provide a class that have a method GetEnumerator() which returns an object that have a MoveNext() method, a Reset() method and a Current property.
Indeed, you do not need to implement neither IEnumerable nor IEnumerator.
Some derived points:
foreach does not need to know the collection length so allows to iterate through a "stream" or a kind of "elements producer".
foreach calls virtual methods on the iterator (the most of the time) so can perform less well than for.
It depends on what you are doing, and what you need.
If you are iterating through a collection of items, and do not care about the index values then foreach is more convenient, easier to write and safer: you can't get the number of items wrong.
If you need to process every second item in a collection for example, or process them ion the reverse order, then a for loop is the only practical way.
The biggest differences are that a foreach loop processes an instance of each element in a collection in turn, while a for loop can work with any data and is not restricted to collection elements alone. This means that a for loop can modify a collection - which is illegal and will cause an error in a foreach loop.
For more detail, see MSDN : foreach and for
Difference Between For and For Each Loop in C#
For Loops executes a block of code until an expression returns false while ForEach loop executed a block of code through the items in object collections.
For loop can execute with object collections or without any object collections while ForEach loop can execute with object collections only.
The for loop is a normal loop construct which can be used for multiple purposes where as foreach is designed to work only on Collections or IEnumerables object.
foreach is useful if you have a array or other IEnumerable Collection of data. but for can be used for access elements of an array that can be accessed by their index.
A for loop is useful when you have an indication or determination, in advance, of how many times you want a loop to run. As an example, if you need to perform a process for each day of the week, you know you want 7 loops.
A foreach loop is when you want to repeat a process for all pieces of a collection or array, but it is not important specifically how many times the loop runs. As an example, you are formatting a list of favorite books for users. Every user may have a different number of books, or none, and we don't really care how many it is, we just want the loop to act on all of them.
The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.
There is a need to specify the loop bounds (minimum or maximum). Following is a code example of a simple for loop that starts 0 till <= 5.
we look at foreach in detail. What looks like a simple loop on the outside is actually a complex data structure called an enumerator:
An enumerator is a data structure with a Current property, a MoveNext method, and a Reset method. The Current property holds the value of the current element, and every call to MoveNext advances the enumerator to the next item in the sequence.
Enumerators are great because they can handle any iterative data structure. In fact, they are so powerful that all of LINQ is built on top of enumerators.
But the disadvantage of enumerators is that they require calls to Current and MoveNext for every element in the sequence. All those method calls add up, especially in mission-critical code.
Conversely, the for-loop only has to call get_Item for every element in the list. That’s one method call less than the foreach-loop, and the difference really shows.
So when should you use a foreach-loop, and when should you use a for-loop?
Here’s what you need to do:
When you’re using LINQ, use foreach
When you’re working with very large computed sequences of values, use foreach
When performance isn’t an issue, use foreach
But if you want top performance, use a for-loop instead
The major difference between the for and foreach loop in c# we understand by its working:
The for loop:
The for loop's variable always be integer only.
The For Loop executes the statement or block of statements repeatedly until specified expression evaluates to false.
In for loop we have to specify the loop's boundary ( maximum or minimum).-------->We can say this is the limitation of the for loop.
The foreach loop:
In the case of the foreach loop the variable of the loop while be same as the type of values under the array.
The Foreach statement repeats a group of embedded statements for each element in an array or an object collection.
In foreach loop, You do not need to specify the loop bounds minimum or maximum.--->
here we can say that this is the advantage of the for each loop.
I prefer the FOR loop in terms of performance. FOREACH is a little slow when you go with more number of items.
If you perform more business logic with the instance then FOREACH performs faster.
Demonstration:
I created a list of 10000000 instances and looping with FOR and FOREACH.
Time took to loop:
FOREACH -> 53.852ms
FOR -> 28.9232ms
Below is the sample code.
class Program
{
static void Main(string[] args)
{
List<TestClass> lst = new List<TestClass>();
for (int i = 1; i <= 10000000; i++)
{
TestClass obj = new TestClass() {
ID = i,
Name = "Name" + i.ToString()
};
lst.Add(obj);
}
DateTime start = DateTime.Now;
foreach (var obj in lst)
{
//obj.ID = obj.ID + 1;
//obj.Name = obj.Name + "1";
}
DateTime end = DateTime.Now;
var first = end.Subtract(start).TotalMilliseconds;
start = DateTime.Now;
for (int j = 0; j<lst.Count;j++)
{
//lst[j].ID = lst[j].ID + 1;
//lst[j].Name = lst[j].Name + "1";
}
end = DateTime.Now;
var second = end.Subtract(start).TotalMilliseconds;
}
}
public class TestClass
{
public long ID { get; set; }
public string Name { get; set; }
}
If I uncomment the code inside the loop:
Then, time took to loop:
FOREACH -> 2564.1405ms
FOR -> 2753.0017ms
Conclusion
If you do more business logic with the instance, then FOREACH is recommended.
If you are not doing much logic with the instance, then FOR is recommended.
Many answers are already there, I just need to identify one difference which is not there.
for loop is fail-safe while foreach loop is fail-fast.
Fail-fast iteration throws ConcurrentModificationException if iteration and modification are done at the same time in object.
However, fail-safe iteration keeps the operation safe from failing even if the iteration goes in infinite loop.
public class ConcurrentModification {
public static void main(String[] args) {
List<String> str = new ArrayList<>();
for(int i=0; i<1000; i++){
str.add(String.valueOf(i));
}
/**
* this for loop is fail-safe. It goes into infinite loop but does not fail.
*/
for(int i=0; i<str.size(); i++){
System.out.println(str.get(i));
str.add(i+ " " + "10");
}
/**
* throws ConcurrentModificationexception
for(String st: str){
System.out.println(st);
str.add("10");
}
*/
/* throws ConcurrentModificationException
Iterator<String> itr = str.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
str.add("10");
}*/
}
}
Hope this helps to understand the difference between for and foreach loop through different angle.
I found a good blog to go through the differences between fail-safe and fail-fast, if anyone interested:
You can use the foreach for an simple array like
int[] test = { 0, 1, 2, 3, ...};
And you can use the for when you have a 2D array
int[][] test = {{1,2,3,4},
{5,2,6,5,8}};
foreach syntax is quick and easy. for syntax is a little more complex, but is also more flexible.
foreach is useful when iterating all of the items in a collection. for is useful when iterating overall or a subset of items.
The foreach iteration variable which provides each collection item, is READ-ONLY, so we can't modify the items as they are iterated. Using the for syntax, we can modify the items as needed.
Bottom line- use foreach to quickly iterate all of the items in a collection. Use for to iterate a subset of the items of the collection or to modify the items as they are iterated.
simple difference between for and foreach
for loop is working with values. it must have condition then increment and intialization also. you have to knowledge about 'how many times loop repeated'.
foreach is working with objects and enumaretors. no need to knowledge how many times loop repeated.
The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface. The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
One important thing related with foreach is that , foreach iteration variable cannot be updated(or assign new value) in loop body.
for example :
List<string> myStrlist = new List<string>() { "Sachin", "Ganguly", "Dravid" };
foreach(string item in myStrlist)
{
item += " cricket"; // ***Not Possible***
}

Which loop to use, for or do/while?

Using C# (or VB.NET) which loop (for loop or do/while loop) should be used when a counter is required?
Does it make a difference if the loop should only iterate a set number of times or through a set range?
Scenario A - The for loop
for (int iLoop = 0; iLoop < int.MaxValue; iLoop++)
{
//Maybe do work here
//Test criteria
if (Criteria)
{
//Exit the loop
break;
}
//Maybe do work here
}
Advantages
Counter is declared as part of loop
Easy to implement counter range
Disadvantages
Have to use an if to leave the loop
Scenario B - The do/while loop
int iLoop = 0;
do
{
//Increment the counter
iLoop++;
//Do work here
} while (Criteria);
or
int iLoop = 0;
while (Criteria)
{
//Increment the counter
iLoop++;
//Do work here
}
Advantages
Leaving the loop is part of the loop structure
Choice to evaluate before or after loop block
Disadvantages
Have to manage the counter manually
Just for completeness, you could also use option D:
for (int iLoop = 0; Criteria; iLoop++)
{
// work here
}
(where Criteria is "to keep running")
the condition in a for loop doesn't have to involve iLoop. Unusual, though, but quite cute - only evaluates before work, though.
How about the best of both worlds:
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
Edit: Now that I think about it, I suppose comparing against int.MaxValue wasn't part of the criteria, but something to emulate an endless for loop, in that case you could just use:
for (int iLoop = 0; !Criterea; iLoop++)
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++) {
//Do work here...
}
Instead of a dummy criteria in the for loop, you can use the actual criteria that you want to use for the loop:
Scenario A2 - the for loop with custom criteria:
for (int iLoop = 0; Criteria; iLoop++) {
// do work here
}
This is equivalent to:
{
int iLoop = 0;
while (Criteria) {
// do work here
iLoop++;
}
}
If you have a loop counter, you should generally use a for loop to make that clearer.
I ususually use for, cause it's simple. I use while when counter is needed after or before loop or if using for is impossible.
You can always add the exit criteria to for loop:
for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++)
{
//Maybe do work here
}
I would really go for whatever looks most readable in your particular case.
There's no reason not to use a for loop in this case. Even if you have other criteria, it's perfectly valid to write:
for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++) { ... }
for loops consist of the following:
for ( initialization; condition; action )
you don’t need an extra if to check your criteria, what do you think is i < value? it’s nothing more than a criteria.
i use loops when they fit the problem, there’s no definite answer
Write some test cases and see which works best for you. Have a look a this link: .Net/C# Loop Performance Test (FOR, FOREACH, LINQ, & Lambda)
Personally I would go with the for loop.
It is better to read, more commonly used and very optimized.
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
{
// Do Work
}
Edit: int.MaxValue && !Criteria <- a definietely better approach than my initial one ;)
I'd tend to use for if I'm actually using the counter in the loop, say as an index into an array, and as part of the criteria, i.e. "stop at the end of the array" rather than "just don't overflow".
If I'm looping over something with unknown length, such as lines in a file, or just maintaining the counter to use the total after the loop, then I'll use do or while.
However, it really comes down to what's more readable for a particular situation. I expect that you'd struggle to tell from the compiled IL which version was used.
((((difference b/w while and do while--> let me tell you with one example :
if a person going into a hall to fix a bomb inside the hall, he must be checked when getting in.. in another case if a person going into a hall to steal something from there he must have been checked when coming out of the hall.. so based on the process only we have to use our looping condition....))))
The for loop can execute a block of code for a fixed or given number of times.if your counter variable depends on that block of code(means inside the looping condition), you can use the for loop
At least for me i use for() when i need to traverse an array and when no breaking is needed. And do() and while() when i need to process something for an unknown time.

In .NET, which loop runs faster, 'for' or 'foreach'?

In C#/VB.NET/.NET, which loop runs faster, for or foreach?
Ever since I read that a for loop works faster than a foreach loop a long time ago I assumed it stood true for all collections, generic collections, all arrays, etc.
I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended.
What would be ideal is to have each scenario listed and the best solution for the same.
For example (just an example of how it should be):
for iterating an array of 1000+
strings - for is better than foreach
for iterating over IList (non generic) strings - foreach is better
than for
A few references found on the web for the same:
Original grand old article by Emmanuel Schanzer
CodeProject FOREACH Vs. FOR
Blog - To foreach or not to foreach, that is the question
ASP.NET forum - NET 1.1 C# for vs foreach
[Edit]
Apart from the readability aspect of it, I am really interested in facts and figures. There are applications where the last mile of performance optimization squeezed do matter.
Patrick Smacchia blogged about this last month, with the following conclusions:
for loops on List are a bit more than 2 times cheaper than foreach
loops on List.
Looping on array is around 2 times cheaper than looping on List.
As a consequence, looping on array using for is 5 times cheaper
than looping on List using foreach
(which I believe, is what we all do).
First, a counter-claim to Dmitry's (now deleted) answer. For arrays, the C# compiler emits largely the same code for foreach as it would for an equivalent for loop. That explains why for this benchmark, the results are basically the same:
using System;
using System.Diagnostics;
using System.Linq;
class Test
{
const int Size = 1000000;
const int Iterations = 10000;
static void Main()
{
double[] data = new double[Size];
Random rng = new Random();
for (int i=0; i < data.Length; i++)
{
data[i] = rng.NextDouble();
}
double correctSum = data.Sum();
Stopwatch sw = Stopwatch.StartNew();
for (int i=0; i < Iterations; i++)
{
double sum = 0;
for (int j=0; j < data.Length; j++)
{
sum += data[j];
}
if (Math.Abs(sum-correctSum) > 0.1)
{
Console.WriteLine("Summation failed");
return;
}
}
sw.Stop();
Console.WriteLine("For loop: {0}", sw.ElapsedMilliseconds);
sw = Stopwatch.StartNew();
for (int i=0; i < Iterations; i++)
{
double sum = 0;
foreach (double d in data)
{
sum += d;
}
if (Math.Abs(sum-correctSum) > 0.1)
{
Console.WriteLine("Summation failed");
return;
}
}
sw.Stop();
Console.WriteLine("Foreach loop: {0}", sw.ElapsedMilliseconds);
}
}
Results:
For loop: 16638
Foreach loop: 16529
Next, validation that Greg's point about the collection type being important - change the array to a List<double> in the above, and you get radically different results. Not only is it significantly slower in general, but foreach becomes significantly slower than accessing by index. Having said that, I would still almost always prefer foreach to a for loop where it makes the code simpler - because readability is almost always important, whereas micro-optimisation rarely is.
foreach loops demonstrate more specific intent than for loops.
Using a foreach loop demonstrates to anyone using your code that you are planning to do something to each member of a collection irrespective of its place in the collection. It also shows you aren't modifying the original collection (and throws an exception if you try to).
The other advantage of foreach is that it works on any IEnumerable, where as for only makes sense for IList, where each element actually has an index.
However, if you need to use the index of an element, then of course you should be allowed to use a for loop. But if you don't need to use an index, having one is just cluttering your code.
There are no significant performance implications as far as I'm aware. At some stage in the future it might be easier to adapt code using foreach to run on multiple cores, but that's not something to worry about right now.
Any time there's arguments over performance, you just need to write a small test so that you can use quantitative results to support your case.
Use the StopWatch class and repeat something a few million times, for accuracy. (This might be hard without a for loop):
using System.Diagnostics;
//...
Stopwatch sw = new Stopwatch()
sw.Start()
for(int i = 0; i < 1000000;i ++)
{
//do whatever it is you need to time
}
sw.Stop();
//print out sw.ElapsedMilliseconds
Fingers crossed the results of this show that the difference is negligible, and you might as well just do whatever results in the most maintainable code
It will always be close. For an array, sometimes for is slightly quicker, but foreach is more expressive, and offers LINQ, etc. In general, stick with foreach.
Additionally, foreach may be optimised in some scenarios. For example, a linked list might be terrible by indexer, but it might be quick by foreach. Actually, the standard LinkedList<T> doesn't even offer an indexer for this reason.
My guess is that it will probably not be significant in 99% of the cases, so why would you choose the faster instead of the most appropriate (as in easiest to understand/maintain)?
There are very good reasons to prefer foreach loops over for loops. If you can use a foreach loop, your boss is right that you should.
However, not every iteration is simply going through a list in order one by one. If he is forbidding for, yes that is wrong.
If I were you, what I would do is turn all of your natural for loops into recursion. That'd teach him, and it's also a good mental exercise for you.
There is unlikely to be a huge performance difference between the two. As always, when faced with a "which is faster?" question, you should always think "I can measure this."
Write two loops that do the same thing in the body of the loop, execute and time them both, and see what the difference in speed is. Do this with both an almost-empty body, and a loop body similar to what you'll actually be doing. Also try it with the collection type that you're using, because different types of collections can have different performance characteristics.
Jeffrey Richter on TechEd 2005:
"I have come to learn over the years the C# compiler is basically a liar to me." .. "It lies about many things." .. "Like when you do a foreach loop..." .. "...that is one little line of code that you write, but what the C# compiler spits out in order to do that it's phenomenal. It puts out a try/finally block in there, inside the finally block it casts your variable to an IDisposable interface, and if the cast suceeds it calls the Dispose method on it, inside the loop it calls the Current property and the MoveNext method repeatedly inside the loop, objects are being created underneath the covers. A lot of people use foreach because it's very easy coding, very easy to do.." .. "foreach is not very good in terms of performance, if you iterated over a collection instead by using square bracket notation, just doing index, that's just much faster, and it doesn't create any objects on the heap..."
On-Demand Webcast:
http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032292286&EventCategory=3&culture=en-US&CountryCode=US
you can read about it in Deep .NET - part 1 Iteration
it's cover the results (without the first initialization) from .NET source code all the way to the disassembly.
for example - Array Iteration with a foreach loop:
and - list iteration with foreach loop:
and the end results:
In cases where you work with a collection of objects, foreach is better, but if you increment a number, a for loop is better.
Note that in the last case, you could do something like:
foreach (int i in Enumerable.Range(1, 10))...
But it certainly doesn't perform better, it actually has worse performance compared to a for.
This should save you:
public IEnumerator<int> For(int start, int end, int step) {
int n = start;
while (n <= end) {
yield n;
n += step;
}
}
Use:
foreach (int n in For(1, 200, 4)) {
Console.WriteLine(n);
}
For greater win, you may take three delegates as parameters.
The differences in speed in a for- and a foreach-loop are tiny when you're looping through common structures like arrays, lists, etc, and doing a LINQ query over the collection is almost always slightly slower, although it's nicer to write! As the other posters said, go for expressiveness rather than a millisecond of extra performance.
What hasn't been said so far is that when a foreach loop is compiled, it is optimised by the compiler based on the collection it is iterating over. That means that when you're not sure which loop to use, you should use the foreach loop - it will generate the best loop for you when it gets compiled. It's more readable too.
Another key advantage with the foreach loop is that if your collection implementation changes (from an int array to a List<int> for example) then your foreach loop won't require any code changes:
foreach (int i in myCollection)
The above is the same no matter what type your collection is, whereas in your for loop, the following will not build if you changed myCollection from an array to a List:
for (int i = 0; i < myCollection.Length, i++)
This has the same two answers as most "which is faster" questions:
1) If you don't measure, you don't know.
2) (Because...) It depends.
It depends on how expensive the "MoveNext()" method is, relative to how expensive the "this[int index]" method is, for the type (or types) of IEnumerable that you will be iterating over.
The "foreach" keyword is shorthand for a series of operations - it calls GetEnumerator() once on the IEnumerable, it calls MoveNext() once per iteration, it does some type checking, and so on. The thing most likely to impact performance measurements is the cost of MoveNext() since that gets invoked O(N) times. Maybe it's cheap, but maybe it's not.
The "for" keyword looks more predictable, but inside most "for" loops you'll find something like "collection[index]". This looks like a simple array indexing operation, but it's actually a method call, whose cost depends entirely on the nature of the collection that you're iterating over. Probably it's cheap, but maybe it's not.
If the collection's underlying structure is essentially a linked list, MoveNext is dirt-cheap, but the indexer might have O(N) cost, making the true cost of a "for" loop O(N*N).
"Are there any arguments I could use to help me convince him the for loop is acceptable to use?"
No, if your boss is micromanaging to the level of telling you what programming language constructs to use, there's really nothing you can say. Sorry.
Every language construct has an appropriate time and place for usage. There is a reason the C# language has a four separate iteration statements - each is there for a specific purpose, and has an appropriate use.
I recommend sitting down with your boss and trying to rationally explain why a for loop has a purpose. There are times when a for iteration block more clearly describes an algorithm than a foreach iteration. When this is true, it is appropriate to use them.
I'd also point out to your boss - Performance is not, and should not be an issue in any practical way - it's more a matter of expression the algorithm in a succinct, meaningful, maintainable manner. Micro-optimizations like this miss the point of performance optimization completely, since any real performance benefit will come from algorithmic redesign and refactoring, not loop restructuring.
If, after a rational discussion, there is still this authoritarian view, it is up to you as to how to proceed. Personally, I would not be happy working in an environment where rational thought is discouraged, and would consider moving to another position under a different employer. However, I strongly recommend discussion prior to getting upset - there may just be a simple misunderstanding in place.
It probably depends on the type of collection you are enumerating and the implementation of its indexer. In general though, using foreach is likely to be a better approach.
Also, it'll work with any IEnumerable - not just things with indexers.
Whether for is faster than foreach is really besides the point. I seriously doubt that choosing one over the other will make a significant impact on your performance.
The best way to optimize your application is through profiling of the actual code. That will pinpoint the methods that account for the most work/time. Optimize those first. If performance is still not acceptable, repeat the procedure.
As a general rule I would recommend to stay away from micro optimizations as they will rarely yield any significant gains. Only exception is when optimizing identified hot paths (i.e. if your profiling identifies a few highly used methods, it may make sense to optimize these extensively).
It is what you do inside the loop that affects perfomance, not the actual looping construct (assuming your case is non-trivial).
The two will run almost exactly the same way. Write some code to use both, then show him the IL. It should show comparable computations, meaning no difference in performance.
In most cases there's really no difference.
Typically you always have to use foreach when you don't have an explicit numerical index, and you always have to use for when you don't actually have an iterable collection (e.g. iterating over a two-dimensional array grid in an upper triangle). There are some cases where you have a choice.
One could argue that for loops can be a little more difficult to maintain if magic numbers start to appear in the code. You should be right to be annoyed at not being able to use a for loop and have to build a collection or use a lambda to build a subcollection instead just because for loops have been banned.
It seems a bit strange to totally forbid the use of something like a for loop.
There's an interesting article here that covers a lot of the performance differences between the two loops.
I would say personally I find foreach a bit more readable over for loops but you should use the best for the job at hand and not have to write extra long code to include a foreach loop if a for loop is more appropriate.
You can really screw with his head and go for an IQueryable .foreach closure instead:
myList.ForEach(c => Console.WriteLine(c.ToString());
for has more simple logic to implement so it's faster than foreach.
Unless you're in a specific speed optimization process, I would say use whichever method produces the easiest to read and maintain code.
If an iterator is already setup, like with one of the collection classes, then the foreach is a good easy option. And if it's an integer range you're iterating, then for is probably cleaner.
Jeffrey Richter talked the performance difference between for and foreach on a recent podcast: http://pixel8.infragistics.com/shows/everything.aspx#Episode:9317
I did test it a while ago, with the result that a for loop is much faster than a foreach loop. The cause is simple, the foreach loop first needs to instantiate an IEnumerator for the collection.
I found the foreach loop which iterating through a List faster. See my test results below. In the code below I iterate an array of size 100, 10000 and 100000 separately using for and foreach loop to measure the time.
private static void MeasureTime()
{
var array = new int[10000];
var list = array.ToList();
Console.WriteLine("Array size: {0}", array.Length);
Console.WriteLine("Array For loop ......");
var stopWatch = Stopwatch.StartNew();
for (int i = 0; i < array.Length; i++)
{
Thread.Sleep(1);
}
stopWatch.Stop();
Console.WriteLine("Time take to run the for loop is {0} millisecond", stopWatch.ElapsedMilliseconds);
Console.WriteLine(" ");
Console.WriteLine("Array Foreach loop ......");
var stopWatch1 = Stopwatch.StartNew();
foreach (var item in array)
{
Thread.Sleep(1);
}
stopWatch1.Stop();
Console.WriteLine("Time take to run the foreach loop is {0} millisecond", stopWatch1.ElapsedMilliseconds);
Console.WriteLine(" ");
Console.WriteLine("List For loop ......");
var stopWatch2 = Stopwatch.StartNew();
for (int i = 0; i < list.Count; i++)
{
Thread.Sleep(1);
}
stopWatch2.Stop();
Console.WriteLine("Time take to run the for loop is {0} millisecond", stopWatch2.ElapsedMilliseconds);
Console.WriteLine(" ");
Console.WriteLine("List Foreach loop ......");
var stopWatch3 = Stopwatch.StartNew();
foreach (var item in list)
{
Thread.Sleep(1);
}
stopWatch3.Stop();
Console.WriteLine("Time take to run the foreach loop is {0} millisecond", stopWatch3.ElapsedMilliseconds);
}
UPDATED
After #jgauffin suggestion I used #johnskeet code and found that the for loop with array is faster than following,
Foreach loop with array.
For loop with list.
Foreach loop with list.
See my test results and code below,
private static void MeasureNewTime()
{
var data = new double[Size];
var rng = new Random();
for (int i = 0; i < data.Length; i++)
{
data[i] = rng.NextDouble();
}
Console.WriteLine("Lenght of array: {0}", data.Length);
Console.WriteLine("No. of iteration: {0}", Iterations);
Console.WriteLine(" ");
double correctSum = data.Sum();
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < Iterations; i++)
{
double sum = 0;
for (int j = 0; j < data.Length; j++)
{
sum += data[j];
}
if (Math.Abs(sum - correctSum) > 0.1)
{
Console.WriteLine("Summation failed");
return;
}
}
sw.Stop();
Console.WriteLine("For loop with Array: {0}", sw.ElapsedMilliseconds);
sw = Stopwatch.StartNew();
for (var i = 0; i < Iterations; i++)
{
double sum = 0;
foreach (double d in data)
{
sum += d;
}
if (Math.Abs(sum - correctSum) > 0.1)
{
Console.WriteLine("Summation failed");
return;
}
}
sw.Stop();
Console.WriteLine("Foreach loop with Array: {0}", sw.ElapsedMilliseconds);
Console.WriteLine(" ");
var dataList = data.ToList();
sw = Stopwatch.StartNew();
for (int i = 0; i < Iterations; i++)
{
double sum = 0;
for (int j = 0; j < dataList.Count; j++)
{
sum += data[j];
}
if (Math.Abs(sum - correctSum) > 0.1)
{
Console.WriteLine("Summation failed");
return;
}
}
sw.Stop();
Console.WriteLine("For loop with List: {0}", sw.ElapsedMilliseconds);
sw = Stopwatch.StartNew();
for (int i = 0; i < Iterations; i++)
{
double sum = 0;
foreach (double d in dataList)
{
sum += d;
}
if (Math.Abs(sum - correctSum) > 0.1)
{
Console.WriteLine("Summation failed");
return;
}
}
sw.Stop();
Console.WriteLine("Foreach loop with List: {0}", sw.ElapsedMilliseconds);
}
A powerful and precise way to measure time is by using the BenchmarkDotNet library.
In the following sample, I did a loop on 1,000,000,000 integer records on for/foreach and measured it with BenchmarkDotNet:
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public class Program
{
public static void Main()
{
BenchmarkRunner.Run<LoopsBenchmarks>();
}
}
[MemoryDiagnoser]
public class LoopsBenchmarks
{
private List<int> arr = Enumerable.Range(1, 1_000_000_000).ToList();
[Benchmark]
public void For()
{
for (int i = 0; i < arr.Count; i++)
{
int item = arr[i];
}
}
[Benchmark]
public void Foreach()
{
foreach (int item in arr)
{
}
}
}
And here are the results:
Conclusion
In the example above we can see that for loop is slightly faster than foreach loop for lists. We can also see that both use the same memory allocation.
I wouldn't expect anyone to find a "huge" performance difference between the two.
I guess the answer depends on the whether the collection you are trying to access has a faster indexer access implementation or a faster IEnumerator access implementation. Since IEnumerator often uses the indexer and just holds a copy of the current index position, I would expect enumerator access to be at least as slow or slower than direct index access, but not by much.
Of course this answer doesn't account for any optimizations the compiler may implement.

C# loop - break vs. continue

In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?
Example:
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//continue;
}
}
break will exit the loop completely, continue will just skip the current iteration.
For example:
for (int i = 0; i < 10; i++) {
if (i == 0) {
break;
}
DoSomeThingWith(i);
}
The break will cause the loop to exit on the first iteration - DoSomeThingWith will never be executed. This here:
for (int i = 0; i < 10; i++) {
if(i == 0) {
continue;
}
DoSomeThingWith(i);
}
Will not execute DoSomeThingWith for i = 0, but the loop will continue and DoSomeThingWith will be executed for i = 1 to i = 9.
A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases.
break loop - looping is broken and stops.
continue loop - loop continues to execute with the next iteration.
break causes the program counter to jump out of the scope of the innermost loop
for(i = 0; i < 10; i++)
{
if(i == 2)
break;
}
Works like this
for(i = 0; i < 10; i++)
{
if(i == 2)
goto BREAK;
}
BREAK:;
continue jumps to the end of the loop. In a for loop, continue jumps to the increment expression.
for(i = 0; i < 10; i++)
{
if(i == 2)
continue;
printf("%d", i);
}
Works like this
for(i = 0; i < 10; i++)
{
if(i == 2)
goto CONTINUE;
printf("%d", i);
CONTINUE:;
}
When to use break vs continue?
Break - We're leaving the loop forever and breaking up forever. Good bye.
Continue - means that you're gonna give today a rest and sort it all out tomorrow (i.e. skip the current iteration)!
(Corny stories ¯¯\(ツ)/¯¯ and pics but hopefully helps you remember.
Grip Alert: No idea why those words are being used. If you want to skip the iteration, why not use the word skip instead of continue? This entire Stack overflow question and 1000s of developers would not be confused if the proper name was given.)
break would stop the foreach loop completely, continue would skip to the next DataRow.
There are more than a few people who don't like break and continue. The latest complaint I saw about them was in JavaScript: The Good Parts by Douglas Crockford. But I find that sometimes using one of them really simplifies things, especially if your language doesn't include a do-while or do-until style of loop.
I tend to use break in loops that are searching a list for something. Once found, there's no point in continuing, so you might as well quit.
I use continue when doing something with most elements of a list, but still want to skip over a few.
The break statement also comes in handy when polling for a valid response from somebody or something. Instead of:
Ask a question
While the answer is invalid:
Ask the question
You could eliminate some duplication and use:
While True:
Ask a question
If the answer is valid:
break
The do-until loop that I mentioned before is the more elegant solution for that particular problem:
Do:
Ask a question
Until the answer is valid
No duplication, and no break needed either.
All have given a very good explanation. I am still posting my answer just to give an example if that can help.
// break statement
for (int i = 0; i < 5; i++) {
if (i == 3) {
break; // It will force to come out from the loop
}
lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}
Here is the output:
0[Printed] 1[Printed] 2[Printed]
So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3
//continue statement
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // It will take the control to start point of loop
}
lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}
Here is the output:
0[Printed] 1[Printed] 2[Printed] 4[Printed]
So 3[Printed] will not be displayed as there is continue when i == 3
Break
Break forces a loop to exit immediately.
Continue
This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.
Simple answer:
Break exits the loop immediately.
Continue starts processing the next item. (If there are any, by jumping to the evaluating line of the for/while)
By example
foreach(var i in Enumerable.Range(1,3))
{
Console.WriteLine(i);
}
Prints 1, 2, 3 (on separate lines).
Add a break condition at i = 2
foreach(var i in Enumerable.Range(1,3))
{
if (i == 2)
break;
Console.WriteLine(i);
}
Now the loop prints 1 and stops.
Replace the break with a continue.
foreach(var i in Enumerable.Range(1,3))
{
if (i == 2)
continue;
Console.WriteLine(i);
}
Now to loop prints 1 and 3 (skipping 2).
Thus, break stops the loop, whereas continue skips to the next iteration.
Ruby unfortunately is a bit different.
PS: My memory is a bit hazy on this so apologies if I'm wrong
instead of break/continue, it has break/next, which behave the same in terms of loops
Loops (like everything else) are expressions, and "return" the last thing that they did. Most of the time, getting the return value from a loop is pointless, so everyone just does this
a = 5
while a < 10
a + 1
end
You can however do this
a = 5
b = while a < 10
a + 1
end # b is now 10
HOWEVER, a lot of ruby code 'emulates' a loop by using a block.
The canonical example is
10.times do |x|
puts x
end
As it is much more common for people to want to do things with the result of a block, this is where it gets messy.
break/next mean different things in the context of a block.
break will jump out of the code that called the block
next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. This doesn't make any sense without examples.
def timesten
10.times{ |t| puts yield t }
end
timesten do |x|
x * 2
end
# will print
2
4
6
8 ... and so on
timesten do |x|
break
x * 2
end
# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped
timesten do |x|
break 5
x * 2
end
# This is the same as above. it's "returning" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5
timesten do |x|
next 5
x * 2
end
# this would print
5
5
5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.
So yeah. Ruby is awesome, but it has some awful corner-cases. This is the second worst one I've seen in my years of using it :-)
Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.
To break completely out of a foreach loop, break is used;
To go to the next iteration in the loop, continue is used;
Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.
Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.
if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.
for(int i = 0; i < list.Count; i++){
if(i == 5)
i = list.Count; //it will make "i<list.Count" false and loop will exit
}
Since the example written here are pretty simple for understanding the concept I think it's also a good idea to look at the more practical version of the continue statement being used.
For example:
we ask the user to enter 5 unique numbers if the number is already entered we give them an error and we continue our program.
static void Main(string[] args)
{
var numbers = new List<int>();
while (numbers.Count < 5)
{
Console.WriteLine("Enter 5 uniqe numbers:");
var number = Convert.ToInt32(Console.ReadLine());
if (numbers.Contains(number))
{
Console.WriteLine("You have already entered" + number);
continue;
}
numbers.Add(number);
}
numbers.Sort();
foreach(var number in numbers)
{
Console.WriteLine(number);
}
}
lets say the users input were 1,2,2,2,3,4,5.the result printed would be:
1,2,3,4,5
Why? because every time user entered a number that was already on the list, our program ignored it and didn't add what's already on the list to it.
Now if we try the same code but without continue statement and let's say with the same input from the user which was 1,2,2,2,3,4,5.
the output would be :
1,2,2,2,3,4
Why? because there was no continue statement to let our program know it should ignore the already entered number.
Now for the Break statement, again I think its the best to show by example. For example:
Here we want our program to continuously ask the user to enter a number. We want the loop to terminate when the user types “ok" and at the end Calculate the sum of all the previously entered numbers and display it on the console.
This is how the break statement is used in this example:
{
var sum = 0;
while (true)
{
Console.Write("Enter a number (or 'ok' to exit): ");
var input = Console.ReadLine();
if (input.ToLower() == "ok")
break;
sum += Convert.ToInt32(input);
}
Console.WriteLine("Sum of all numbers is: " + sum);
}
The program will ask the user to enter a number till the user types "OK" and only after that, the result would be shown. Why?
because break statement finished or stops the ongoing process when it has reached the condition needed.
if there was no break statement there, the program would keep running and nothing would happen when the user typed "ok".
I recommend copying this code and trying to remove or add these statements and see the changes yourself.
As for other languages:
'VB
For i=0 To 10
If i=5 then Exit For '= break in C#;
'Do Something for i<5
next
For i=0 To 10
If i=5 then Continue For '= continue in C#
'Do Something for i<>5...
Next

Categories

Resources