Concatenating strings in C, which method is more efficient?

后端 未结 10 946
迷失自我
迷失自我 2020-11-28 19:51

I came across these two methods to concatenate strings:

Common part:

char* first= \"First\";
char* second = \"Second\";
char* both = malloc(strlen(fi         


        
10条回答
  •  半阙折子戏
    2020-11-28 20:25

    The difference is unlikely to matter:

    • If your strings are small, the malloc will drown out the string concatenations.
    • If your strings are large, the time spent copying the data will drown out the differences between strcat / sprintf.

    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".

提交回复
热议问题