10 Replies - 651 Views - Last Post: 11 April 2011 - 01:08 PM Rate Topic: -----

#1 blank_program  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 282
  • Joined: 22-July 09

Performance question concerning loops: For and while

Posted 10 April 2011 - 01:51 PM

So this might be better in programmer's lounge I am not sure so I posted it here.

Recently I was writing some code that loops until the specified string length is reached. My question is this: is it more efficient to use a for loop or a while loop. Currently I am using only short lengths and in other code I tend to use for loops when I need one. When it is more appropriate to use while or do while loops instead of a for loop? Does one give better performance or are they about equal?

I tried to check Google but couldn't find much information on this topic so any input is welcome.

Is This A Good Question/Topic? 0
  • +

Replies To: Performance question concerning loops: For and while

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5529
  • View blog
  • Posts: 11,839
  • Joined: 02-June 10

Re: Performance question concerning loops: For and while

Posted 10 April 2011 - 01:59 PM

You could actually test that empirically yourself.

Write one loop one way and output the time it takes to go through 100,000 iterations.

Then do the same with the other loop.

Being able to test your own alternative code concepts, rather than ask others is vital. Especially when it is something so easily tested.
Was This Post Helpful? 0
  • +
  • -

#3 blank_program  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 282
  • Joined: 22-July 09

Re: Performance question concerning loops: For and while

Posted 10 April 2011 - 02:15 PM

What method would I use to test the time though is there something within Visual Studio 2010 to time it with?
Was This Post Helpful? 0
  • +
  • -

#4 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 991
  • View blog
  • Posts: 971
  • Joined: 30-September 10

Re: Performance question concerning loops: For and while

Posted 10 April 2011 - 02:33 PM

You can use the Stopwatch Class to measure the time taken for each to execute :)
Was This Post Helpful? 2
  • +
  • -

#5 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6064
  • View blog
  • Posts: 23,518
  • Joined: 23-August 08

Re: Performance question concerning loops: For and while

Posted 10 April 2011 - 03:12 PM

If Reflector were still free (or if you wanted to do the trial thing), you could examine the generated IL code to compare the implementations.
Was This Post Helpful? 0
  • +
  • -

#6 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Performance question concerning loops: For and while

Posted 10 April 2011 - 05:09 PM

Give this code:
for (int i = 0; i < limit; i++) {
    DoSomething();
}

int w = 0;
while (w < limit) {
    DoSomething();
    w++;
}


Generates this assembly code:
for (int i = 0; i < limit; i++) {
0000002a  xor         edx,edx 
0000002c  mov         dword ptr [ebp-8],edx 
0000002f  nop 
00000030  jmp         0000003B 
    DoSomething();
00000032  call        dword ptr ds:[00542D20h] 
for (int i = 0; i < limit; i++) {
00000038  inc         dword ptr [ebp-8] 
0000003b  mov         eax,dword ptr [ebp-8] 
0000003e  cmp         eax,dword ptr [ebp-4] 
00000041  jl          00000032 
}

int w = 0;
00000043  xor         edx,edx 
00000045  mov         dword ptr [ebp-0Ch],edx 
00000048  nop 
00000049  jmp         00000054 
    DoSomething();
0000004b  call        dword ptr ds:[00542D20h] 
    w++;
00000051  inc         dword ptr [ebp-0Ch] 
while (w < limit) {
00000054  mov         eax,dword ptr [ebp-0Ch] 
00000057  cmp         eax,dword ptr [ebp-4] 
0000005a  jl          0000004B 
}


If you compare them you can see that they generate the exact same op codes, the only difference being the offsets that they use to access values. A for loop is just a easier way to write a while loop when iterating through a fixed size collection (or a specific number of times)
Was This Post Helpful? 0
  • +
  • -

#7 November-06  Icon User is offline

  • D.I.C Regular

Reputation: 46
  • View blog
  • Posts: 395
  • Joined: 04-January 11

Re: Performance question concerning loops: For and while

Posted 11 April 2011 - 01:41 AM

You use the for loop when you are certain of the number of times you want to perform the statements.

If there is no exact number of times, you use the while.

You can also use the while when your condition is of data type boolean or string instead of the usual integer counter.

For example, while(RepeatStatement==true) or while(UserInput=="hi"). When the conditions are like this, there is no way you can use the for loop.
Was This Post Helpful? 0
  • +
  • -

#8 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Performance question concerning loops: For and while

Posted 11 April 2011 - 05:58 AM

View PostNovember-06, on 11 April 2011 - 01:41 AM, said:

For example, while(RepeatStatement==true) or while(UserInput=="hi"). When the conditions are like this, there is no way you can use the for loop.
You don't know what you are talking about.
for(;RepeatStatement == true;) {
    DoSomething();
}

for(;UserInput == "hi";)/> {
    DoOtherThing();
}


Again, for loops are just easy way to write while loops.

This post has been edited by Momerath: 11 April 2011 - 05:58 AM

Was This Post Helpful? 1
  • +
  • -

#9 blank_program  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 282
  • Joined: 22-July 09

Re: Performance question concerning loops: For and while

Posted 11 April 2011 - 12:53 PM

So I tested using 1,000,000 iterations of the same code where I compare a string length to the length the user requests and I ran it requesting a length of 24.

Using this code I get 5012 ms.
while(teststring.Length != Length)
{
    //do something
}



And when I use a for loop I get 4521 ms.
for(int i = 0; i < Length; i++)
{
    //do something
}



So it seems with my short sample the for loop is actually faster. In my current project there isn't a need for performance I was just curious.

Is there a way to pass a method to another method? Seems like an awkward question but for instance if I want to setup a stopwatch method for testing so I don't need to write in the code each time I could just give it a method to loop. Might not be possible but figured I would throw it out there.

In my example I do know the two variable needed by the method, current string length, and desired length.
Was This Post Helpful? 0
  • +
  • -

#10 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5529
  • View blog
  • Posts: 11,839
  • Joined: 02-June 10

Re: Performance question concerning loops: For and while

Posted 11 April 2011 - 01:05 PM

View Postblank_program, on 11 April 2011 - 01:53 PM, said:

So I tested using 1,000,000 iterations of the same code where I compare a string length to the length the user requests and I ran it requesting a length of 24.

Using this code I get 5012 ms.
while(teststring.Length != Length)
{
    //do something
}



And when I use a for loop I get 4521 ms.
for(int i = 0; i < Length; i++)
{
    //do something
}


Those are not equal blocks of code for testing.
The first has a built-in comparrison to be performed that the second does not. I would expect it to take longer because it is doing something the other is not.

To be fair about the comparison you have to use equal blocks.

int test = 0;
while (test < 1000000)
{
   test++;
}

int test1 = 0
for(int Index=0; Index < 1000000; Index++)
{
    test1++;
}

Was This Post Helpful? 1
  • +
  • -

#11 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4490
  • View blog
  • Posts: 7,822
  • Joined: 08-June 10

Re: Performance question concerning loops: For and while

Posted 11 April 2011 - 01:08 PM

@blank_program: I'm afraid that's really not a valid test. You'd need to repeat your test many, many times to average out fluctuations on processor availability and such.

And yes, there is a way to send methods to methods using delegates.

static void Main(string[] args) {
    Console.WriteLine(TimeMethod(ForLoop, 100).TotalMilliseconds);
    Console.ReadKey();
}

static void ForLoop(long times) {
    for (long i = 0; i < times; i++) {
        DoSomething();
    }
}

static void WhileLoop(long times) {
    long i = 0;
    while (i++ < times) {
        DoSomething();
    }
}

private static void DoSomething() {
    Thread.Sleep(1);
}

private static TimeSpan TimeMethod(Action<long> method, long parameter) {
    DateTime mark = DateTime.Now;
    method.Invoke(parameter);
    return DateTime.Now.Subtract(mark);
}


If your methods returned something, you'd use Func instead of Action, and the last of the generic parameters is the return type.

This post has been edited by Curtis Rutland: 11 April 2011 - 01:09 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1