for loop or while loop – which one is faster ?


Once I had a discussion with our colleague. The question was – Which one is faster for loop or while loop ?

I hope most out there may think either one of them will be faster. In this article I will analyses the case for both.

First I am writing a simple C code. A infinite loop using both for and while statements.

Infinite while loop

int main(int argc, char *argv[])
{
 int i;

 while(1){

 }

 return 0;
}

Infinite For loop that is equivalent to the above while loop code.

int main(int argc, char *argv[])
{
 int i;

 for(;;){

 }

 return 0;
}

Now compile it with GCC using following command

$ gcc -O0 -s <source file name> -o <out put filename>

Here:-
-O0 – Tells the compiler not to optimize the code.
-s – Tells the compiler to run till assembler stage and stop
-o – Save the output in this file.

For my surprise both generate the same code as below.

 .text
.globl main
 .type	main, @function
main:
 pushl	%ebp
 movl	%esp, %ebp
 subl	$16, %esp
.L2:
 jmp	.L2
 .size	main, .-main
 .ident	"GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
 .section	.note.GNU-stack,"",@progbits

Hence proven that both infinite loops are same there will be no performance gain in one over other.

Lets look at some other code which involves in some iteration. Again same approach, similar code in C then generate intermediate assembly code and then compare.

For loop code

int main(int argc, char *argv[])
{
 int i;

 for(i=0; i<10; i++){

 }

 return 0;
}

Equivalent while loop code.

int main(int argc, char *argv[])
{
 int i;

 i=0;
 while(i<10){
 i++;
 }

 return 0;
}

Now compile it with GCC using following command

$ gcc -O0 -s <source file name> -o <out put filename>

Both generate the same code as below.

.text
.globl main
 .type	main, @function
main:
 pushl	%ebp
 movl	%esp, %ebp
 subl	$16, %esp
 movl	$0, -4(%ebp)
 jmp	.L2
.L3:
 addl	$1, -4(%ebp)
.L2:
 cmpl	$9, -4(%ebp)
 jle	.L3
 movl	$0, %eax
 leave
 ret
 .size	main, .-main
 .ident	"GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
 .section	.note.GNU-stack,"",@progbits

From this example we can see using while or for will not give you performance gain or size reduction, it is all about programming convenient.

Hope it is useful to you and agree with me.

Leave your comments.

One thought on “for loop or while loop – which one is faster ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s