Reputation: 62234
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
cmd arg1 arg2 arg3
Here's how I woud do it (pseudo-code):
Well, it works but I wonder if using strcat that deliberately is actually efficient/the right way to do it.
Any suggestions?
Upvotes: 0
Views: 1181
Reputation: 23303
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.
Upvotes: 1
Reputation: 399949
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.
Upvotes: 5
Reputation: 792497
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.
Upvotes: 2