Last post Oct 24, 2009 10:47 AM by pl_harish
Oct 23, 2009 02:09 AMfirstname.lastname@example.org|LINK
I have a doubt,
string sArray = new string["a","b","c",.....upto 100 string];
foreach (string temp in sArray)
will this for-each loop create new string object each time it iterates ?
Is there any advantage if I use for loop other thay for-each to iterate through string array/array list etc ??
Oct 23, 2009 02:20 AM|MetalAsp.Net|LINK
There may be a bit of a performance benefit with for loops, however I find foreach more readable. I would go with foreach.
Oct 23, 2009 02:20 AM|ameenkpn|LINK
Yes. it creates a new object every time. but the scope is limited within the for each loop only. so you have no problem. Then foreach is better than ordinary for loop, becoz, for loop, you need to specify the upper and the lower bounds, which is every time
you need to calculate whenever you need to loop.
Oct 23, 2009 02:28 AM|malcolms|LINK
I agree with MetalAsp.Net. The foreach is much easier to read that the for loop. Code readability counts.
Oct 23, 2009 04:55 AM|deepthoughts|LINK
The for loop is better in performance compared to foreach
loop. Please check the following article.
but foreach is lot easier to use and its code is lot more readable.
Now as in most part of your code you need to put in small loops, so its best to use
foreach then to make your code more readable and in these scenarios the performance benefit given by
for loop is not much considerable and prefer to use for
loops in performance critical parts.. Please check the following article.
Oct 24, 2009 10:47 AM|pl_harish|LINK
Given your code,
foreach(string temp.... creates temp everytime.. a new string object.. but within the scope of the loop only.
for(int k=0; k<sArray.length; k++)
doesn't create a new string object..