Concatenating strings in C, which method is more efficient?

后端 未结 10 893
迷失自我
迷失自我 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".

    0 讨论(0)
  • 2020-11-28 20:31
    • strcpy and strcat are much simpler oprations compared to sprintf, which needs to parse the format string
    • strcpy and strcat are small so they will generally be inlined by the compilers, saving even one more extra function call overhead. For example, in llvm strcat will be inlined using a strlen to find copy starting position, followed by a simple store instruction
    0 讨论(0)
  • 2020-11-28 20:36

    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.

    0 讨论(0)
  • 2020-11-28 20:41

    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

    0 讨论(0)
  • 2020-11-28 20:42

    They should be pretty much the same. The difference isn't going to matter. I would go with sprintf since it requires less code.

    0 讨论(0)
  • 2020-11-28 20:42

    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.

    0 讨论(0)
提交回复
热议问题