开发者

Efficient string concatenation in C

Here's my problem: I have an array, which contains a command a[1], followed by several command args a[2], a[3], ...

What I need to do is the following

  • Create a string, consisting of the cmd and a combination of args E.g.:

cmd arg1 arg2 arg3

  • Execute that command-string

Here's how I woud do it (pseudo-code):

  1. Precompute the length of each arg and store it in an array
  2. Get a combination (using GNU Scientific Library)
  3. Compute the size in bytes needed to allocate the string (length of cmd + 1 + lengthof arg1 + 1 + argn-1 + 1) (the +1 generally for the for the blank and at the end for the \0)
  4. Build the string by using strcat
  5. Execute the c开发者_运维百科ommand-string

Well, it works but I wonder if using strcat that deliberately is actually efficient/the right way to do it.

Any suggestions?


No, using strcat() is not efficient since it has to step through the string to find the end each time you call it.

Much better to either do it all at once using snprintf() if you have it (and can squeeze your arguments in there), or do it yourself using direct pointer manipulation.

Of course, for this to matter in practice you need to be running this command very often indeed.


If you've stored the lengths of each component string that you can switch to using memcpy with the correct pointer offsets instead of using strcat which won't have to find that end of the string adn the test each source char against '\0', but other than that there isn't a whole lot more that you can do to make the creation of a concatenated significantly faster.


strcat(), as well as all string manipulation functions from the standard library, is inefficient. this is due to way strings are stored in C, namely zero-terminated, thus each function has to find the end of the string by iterating over each character.

anyway, you are doing a premature optimization: the multiple strcat() calls here will execute really fast compared to the command execution, so you should not worry about the efficiency of your way of concatenating.

before optimizing part of a code, you have to show that it is a bottleneck and that optimizing will really improve execution time. in most cases, there is no need to optimize: it is simply not worth the time spent.


I would do it with sprintf.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜