Please I'd like to know which is better/quicker to process between:
printf("%s", foo);
and
for(int i = 0; i < len; i++)
printf('%c', foo[i]);`
I have noticed that the output is not always the same.
Please I'd like to know which is better/quicker to process between:
printf("%s", foo);
and
for(int i = 0; i < len; i++)
printf('%c', foo[i]);`
I have noticed that the output is not always the same.
The single call printf("%s", foo);
is most likely faster. You only make one function call to printf
instead of n
function calls, each of which has to parse the format string.
Even if the latter was faster, the former is still preferred because it is clearer to the reader.
Performance test it. Trying to come up with any rule that A is faster than B is bad practice. The assumption will become incorrect over time or in slightly different scenarios. Always performance test when optimizing.
Write a test case and test it with a high precision timer. Make sure your performance timer has a high enough granularity to show differences. On Windows you can use QueryPerformanceCounter
. Googling that function should get you started.
Note that there is a syntax error in: for(int i = 0; i < len; i++) printf('%c', foo[i]);
. It should read:
int len = strlen(foo);
for (int i = 0; i < len; i++)
printf("%c", foo[i]);
This loop, assuming the length of foo
fits in a int
, is quite inefficient. printf("%s", foo);
is very likely faster than that, but if you have noticed different output, there is something fishy going on... Maybe len
was not computed properly.
Note also that you could write a potentially more efficient version:
for (int i = 0; i < len; i++)
putchar(foo[i]);
And you could also improve on printf("%s",foo);
with this variant:
fputs(foo, stdout);
But as always, you should test and benchmark on your system to measure actual performance. Some compilers will optimize the printf("%s", foo);
into fputs(foo, stdout);
automatically.
The statement without loop is probably faster than the statement with loop.
for
loop for(int i = 0; i < len ; i++)
printf("%c", foo[i]) ;
In every iteration, i is compared with 'len' and i is incremented after every character is printed.
printf("%s", foo) ;
foo here is basically a pointer to string and it will go on printing every character after foo[0]
until a '\0'
character (or terminating character) is found.
So, in the 2nd case, we save the time to update i
and access foo[i]
with respect to foo[0]
.
To add a disclaimer, the actual performance testing might lead you to results that would depend on the compiler and the operating system you are working on.