>>5
* sizeof(char) is defined by the standard to be 1.
* strcpy is not the proper function to use in this situation.
* Using strcat requires calloc instead of malloc to be used to ensure NULL-termination.
The corrected code has been attached to this message.
____________________________ Attachments:
>>11
Calloc will null all the memory while you only need one first byte for strcat. The way you use strcat is not optimal either.
I mean, if you care about speed, write it so that it works fast, and if you don't - don't use C.
>>13
After first strcat your string will be "one". When you call strcat the second time, it will have to walk this "one" string to find where it ends and where to append your "two". Third call will have to walk "onetwo" to find its end. You don't need that, you already know when string ends when you append something to it. I'm not going to provide assembly, look at the benchmark one post higher.
>>16
Note that strcat in >>14 walking the length of the string is no different from strlen walking the length of the string in >>11, except that it's more clear to the compiler what you're doing (thus enabling additional optimizations, as shown by the performance increase noted in >>14).
The reason assembly was asked for is because gcc, at least, provides internal implementations for most of the string functions (if -fno-builtins isn't specified, all functions used in this thread are builtins) and does some naughty stuff to decrease runtimes[1]. References:
[1] http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Other-Builtins.html
>>22
Even with your naughty optimizations result are still worse than with the last solution, which is just a slight modification of >>5, who thought that subexpression elimination can be applied here (dumbass). You can't make it work that fast using strcat.