-
Efficient Coding Styles
Hey all
been thinking about this a bit reciently.
which of the following would run faster??
------------------------------------------------
printf("Hello World");
-----------------------------------------------
-----------------------------------------------
char * string = "Hello World";
printf("%s", string);
-----------------------------------------------
or
-----------------------------------------------
printf("%s","Hello World");
-----------------------------------------------
I dont particularly want to know for the printf function, but functions in general.. (printf is prob a bad example)
I sometimes find it easier to read the code if it uses the 2nd style..
I figure that once the code is compiled it wouldnt make a difference.
Ive heard that the second style can make it easier for the compiler to compile code, which means the executable would be that little bit faster, Especially if your sending the return value from a function directly into that function:
.. hmm not to good at explainging so heres an example
----------------------------------------------------------------------
func2(func1());
----------------------------------------------------------------------
does anyone have any input?
cheers,
-
First program's c code
Code:
#include <stdio.h>
int main(void)
{
printf("Hello World!\n");
return 0;
}
compiled with -O3 to assembly
Code:
.file "tmp.c"
.version "01.01"
gcc2_compiled.:
.section .rodata
.LC0:
.string "Hello World!\n"
.text
.align 4
.globl main
.type main,@function
main:
pushl %ebp
movl %esp,%ebp
pushl $.LC0
call printf
xorl %eax,%eax
leave
ret
.Lfe1:
.size main,.Lfe1-main
.ident "GCC: (GNU) egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)"
Second program's c code
Code:
#include <stdio.h>
int main(void)
{
char* s = "Hello World!\n";
printf(s);
return 0;
}
Compiled with gcc -O3
Code:
.file "tmp1.c"
.version "01.01"
gcc2_compiled.:
.section .rodata
.LC0:
.string "Hello World!\n"
.text
.align 4
.globl main
.type main,@function
main:
pushl %ebp
movl %esp,%ebp
pushl $.LC0
call printf
xorl %eax,%eax
leave
ret
.Lfe1:
.size main,.Lfe1-main
.ident "GCC: (GNU) egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)"
And surprisingly it is the same assembly output.
-
Agree above,hehe.
I come from china ,and want to learn more.
I feel it is a useful place, I will come here more often.
-
Thanks
hey,
I figured it'd be something like that..
you wouldnt be able to tell me more about compiling to assembly would ya.. it looks interesing.
thanks again,