What would be faster? This:
sprintf(&str[strlen(str)], "Something");
or
strcat(str, "Something");
Is there any performance difference?
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 there's a difference, that difference varies according to compiler flags, computer usage at the time the code is running, library implementation, ..., ...
For your specific case, measure.
Run both snippets a few billion times and time them.
I doubt very much you will find any significant difference.
I like strcat()
better: it clearly conveys the meaning of the code.
strcat
is far faster in this case. Remember that sprintf()
parses the format string character by character looking for % escapes. Compare this to:
strcpy (str + strlen (str), "Something");
for example.
I agree with others: strcat()
should be faster. But for "best-practice", if you really care about speed, you should use neither. You'd better have a struct like:
typedef struct { size_t len, max; char *str; } mystring_t;
to keep track of the end of the string. When you append a string, simply jump to the end and copy it. Double max
if the allocated memory is not large enough. Alternatively, you may have something a bit fancy by packing len
, max
and str
together.