Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcat() vs sprintf()

Tags:

c

coding-style

What would be faster? This:

sprintf(&str[strlen(str)], "Something");

or

strcat(str, "Something");

Is there any performance difference?

like image 990
lxe Avatar asked Nov 20 '09 18:11

lxe


2 Answers

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.

like image 144
Justin Rudd Avatar answered Oct 30 '22 23:10

Justin Rudd


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.

like image 45
James McNellis Avatar answered Oct 31 '22 01:10

James McNellis