I came across these two methods to concatenate strings:
Common part:
char* first= \"First\";
char* second = \"Second\";
char* both = malloc(strlen(fi
The difference is unlikely to matter:
As other posters have mentioned, this is a premature optimization. Concentrate on algorithm design, and only come back to this if profiling shows it to be a performance problem.
That said... I suspect method 1 will be faster. There is some---admittedly small---overhead to parse the sprintf format-string. And strcat is more likely "inline-able".
Don't worry about efficiency: make your code readable and maintainable. I doubt the difference between these methods is going to matter in your program.
I don't know that in case two there's any real concatenation done. Printing them back to back doesn't constitute concatenation.
Tell me though, which would be faster:
1) a) copy string A to new buffer b) copy string B to buffer c) copy buffer to output buffer
or
1)copy string A to output buffer b) copy string b to output buffer
They should be pretty much the same. The difference isn't going to matter. I would go with sprintf
since it requires less code.
Neither is terribly efficient since both methods have to calculate the string length or scan it each time. Instead, since you calculate the strlen()s of the individual strings anyway, put them in variables and then just strncpy() twice.