What would be faster? This:
sprintf(&str[strlen(str)], "Something");
or
strcat(str, "Something");
Is there any performance difference?
strcat would be faster because sprintf has to first scan the string looking for format variables.
But the real win is the fact that everyone knows what strcat is doing - concatenating strings. Using sprintf for concatenation isn't a standard use. And it would cause people to do a double take.
Given the choice between the two, I'd choose strcat; it's certainly more readable and makes your intentions clear. It might also be slightly faster than sprintf, but probably not by much.
But, regardless of which method you choose, you should definitely use snprintf or strncpy for buffer overrun protection.
You tagged this question as both c and c++; if you are using C++, it would be far better to use a std::string instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With