循环内strcat()与sprintf()性能对比:移除$开头字符串变量
Context
I’ve built a program that strips all $-prefixed variables from a string. For example, feeding it [1,2,$1,$2] should return [1,2]. I’m trying to figure out which of these two loop implementations is more performant.
Code Example 1
while (token != NULL) { if (*token != '$') { sprintf(dst, "%s,%s", dst, token); } token = strtok(NULL, "], "); }
Code Example 2
while (token != NULL) { if (*token != '$') { strcat(dst, token); strcat(dst, ","); } token = strtok(NULL, "], "); }
Breakdown
First things first: Code Example 1 is invalid and has undefined behavior. When you use sprintf(dst, "%s,%s", dst, token), you’re using dst as both the input source (for the first %s) and the output buffer. The C standard explicitly says this kind of overlapping buffer usage leads to unpredictable results—your program could crash, corrupt memory, or spit out garbage. So this implementation is a non-starter, regardless of performance.
Now, looking at Code Example 2 (the valid one):
- Every call to
strcathas to scan the entiredststring from start to end to find its null terminator before appending the new content. Asdstgets longer, eachstrcattakes more time, making the overall process O(n²) (where n is the length of your final string). That’s not great for large inputs, but it’s at least correct.
If we hypothetically ignored the undefined behavior in Example 1, sprintf would still be slower than strcat here. sprintf has to parse the format string, handle variable arguments, and do the same concatenation work as strcat—but with extra overhead from the formatting logic. So even if it were valid, it’s not the faster option.
A Better Performance Approach
Both implementations waste time re-scanning the dst buffer every time. For a faster solution:
- First loop through all your tokens once to calculate the total length of the final string (including commas between valid tokens).
- Allocate a buffer of exactly that size (or use a pre-allocated buffer you know is big enough).
- Keep track of your current position in the buffer, and use
memcpyor direct string copies to write each token and comma without re-scanning the entire buffer. This drops the time complexity to O(n), which is way more efficient for larger inputs.
内容的提问来源于stack exchange,提问作者Sinayra

