sprintf () is designed to handle much more than just strings, strcat () is a specialist. But I suspect that you sweat on trifles. Lines C are fundamentally ineffective in ways that make the differences between the two proposed methods insignificant. Read Joel Spolsky's Back to Basics for details.
This is an example where C ++ is usually better than C. To handle a heavy string using std :: string is likely to be more efficient and certainly safe.
[edit]
[2nd edit] Corrected code (too many iterations in the implementation of line C), timings and conclusion, respectively.
I was surprised by Andrew Bainbridge's remark that std :: string was slower, but he did not publish the full code for this test case. I changed it (synchronization automation) and added the std :: string test. The test was conducted on VC ++ 2008 (native code) with the standard "Release" options (that is, optimized), Athlon dual core, 2.6 GHz. Results:
C string handling = 0.023000 seconds sprintf = 0.313000 seconds std::string = 0.500000 seconds
Thus strcat () is now much faster (your movement may vary depending on the compiler and parameters), despite the inherent C-line inefficiency convention, and supports my initial suggestion that sprintf () carries most of the luggage is not required for this goal. However, it remains the least readable and safe, so when performance is not critical, it has few IMO advantages.
I also tested the implementation of std :: stringstream, which was much slower, but it still makes sense for complex formatting of strings.
Fixed code:
#include <ctime> #include <cstdio> #include <cstring> #include <string> void a(char *first, char *second, char *both) { for (int i = 0; i != 1000000; i++) { strcpy(both, first); strcat(both, " "); strcat(both, second); } } void b(char *first, char *second, char *both) { for (int i = 0; i != 1000000; i++) sprintf(both, "%s %s", first, second); } void c(char *first, char *second, char *both) { std::string first_s(first) ; std::string second_s(second) ; std::string both_s(second) ; for (int i = 0; i != 1000000; i++) both_s = first_s + " " + second_s ; } int main(void) { char* first= "First"; char* second = "Second"; char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char)); clock_t start ; start = clock() ; a(first, second, both); printf( "C string handling = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ; start = clock() ; b(first, second, both); printf( "sprintf = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ; start = clock() ; c(first, second, both); printf( "std::string = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ; return 0; }