Answered by:
for loop uses

Question
-
User-1734040675 posted
Hello all,
May I know uses of for loop performance wise?
ex:
1)for(int i=1;i<=3;i++){ do something }
2) if(i=1) {do something}, if(i=2){do something}, if(i=3) {do something}
performance wise any differences between these two?
Thank you
Tuesday, September 2, 2014 2:41 AM
Answers
-
User-1360095595 posted
One is used to iterate through a list/collection, the other is used to check condition(s). There's no point in asking about performance because they aren't used for the same purpose. Comparing for to foreach would make sense, but not for/if.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, September 2, 2014 2:58 AM
All replies
-
User-1360095595 posted
One is used to iterate through a list/collection, the other is used to check condition(s). There's no point in asking about performance because they aren't used for the same purpose. Comparing for to foreach would make sense, but not for/if.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, September 2, 2014 2:58 AM -
User-1734040675 posted
My point is iterating a list with for loop and without for loop- any difference?
Tuesday, September 2, 2014 3:05 AM -
User-760709272 posted
You might need to give a clearer example, however you can test this for yourself. Look at the Stopwatch object and how to use it. Now execute each code sample 100,000 by putting it in a loop, then time how long each version takes, then compare. Re-run a few times to get average times.
Tuesday, September 2, 2014 3:34 AM -
User-1360095595 posted
Well, I mean if the loop is large, say 100 or more, would you want to loop or not? Regardless of performance, I would loop.
Anyway, I doubt you'll see any noticeable performance either way.
Tuesday, September 2, 2014 3:34 AM -
User-1151753377 posted
Hi thaqi498,
As far as I know, if you want to achieve the loop, maybe you could try the following code:
int n; switch (n) { case 1: Response.Write("1"); break; case 2: Response.Write("2"); break; case 3: Response.Write("3"); break; case 4: Response.Write("4"); break; }
Notes: the variable n is arbitrarily defined.
Further information about the loop:
http://csharp.net-tutorials.com/basics/loops/
If there’s anything you’d like to know, don’t hesitate to ask.
Best Regards,
Summer
Tuesday, September 2, 2014 9:27 PM