You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

循环内strcat()与sprintf()性能对比:移除$开头字符串变量

Which loop implementation has better performance for removing $-prefixed variables from a string?

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 strcat has to scan the entire dst string from start to end to find its null terminator before appending the new content. As dst gets longer, each strcat takes 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 memcpy or 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:34:35