views:

113

answers:

4

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 command-string

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

Any suggestions?

+2  A: 

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.

Charles Bailey
A: 

I would do it with sprintf.

Macarse
+5  A: 

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.

unwind
+1 for `snprintf`. A nifty feature of `snprintf` is that you can pass in a zero length (and maybe even a NULL buffer address) and it will return the number of bytes you need. A common technique is to call `snprintf()` with 0 length, use the return value to `malloc()` the necessary space, and then call `snprintf()` again using the buffer.
tomlogic
+1  A: 

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.

Adrien Plisson