[英]strcat() vs sprintf()
What would be faster? 什么会更快? This:
这个:
sprintf(&str[strlen(str)], "Something");
or 要么
strcat(str, "Something");
Is there any performance difference? 有任何性能差异吗?
strcat
would be faster because sprintf
has to first scan the string looking for format variables. strcat
会更快,因为sprintf
必须首先扫描字符串以查找格式变量。
But the real win is the fact that everyone knows what strcat
is doing - concatenating strings. 但真正的胜利是每个人都知道
strcat
正在做什么 - 连接字符串。 Using sprintf
for concatenation isn't a standard use. 使用
sprintf
进行连接不是标准用法。 And it would cause people to do a double take. 它会让人们做双重拍摄。
Given the choice between the two, I'd choose strcat
; 鉴于两者之间的选择,我会选择
strcat
; it's certainly more readable and makes your intentions clear. 它肯定更具可读性,使你的意图清晰。 It might also be slightly faster than
sprintf
, but probably not by much. 它也可能比
sprintf
略快,但可能不是很多。
But, regardless of which method you choose, you should definitely use snprintf
or strncpy
for buffer overrun protection. 但是,无论您选择哪种方法,都应该使用
snprintf
或strncpy
进行缓冲区溢出保护。
You tagged this question as both c
and c++
; 你把这个问题标记为
c
和c++
; if you are using C++, it would be far better to use a std::string
instead. 如果您使用的是C ++,那么使用
std::string
会好得多。
If there's a difference, that difference varies according to compiler flags, computer usage at the time the code is running, library implementation, ..., ... 如果存在差异,则该差异根据编译器标志,代码运行时的计算机使用情况,库实现,...,......而有所不同。
For your specific case, measure . 针对您的具体情况,进行衡量 。
Run both snippets a few billion times and time them. 将两个片段运行几十亿次并计时。
I doubt very much you will find any significant difference. 我非常怀疑你会发现任何重大的不同。
I like strcat()
better: it clearly conveys the meaning of the code. 我更喜欢
strcat()
:它清楚地传达了代码的含义。
strcat
is far faster in this case. 在这种情况下,
strcat
要快得多。 Remember that sprintf()
parses the format string character by character looking for % escapes. 请记住,
sprintf()
按字符解析格式字符串,查找%escapes。 Compare this to: 比较这个:
strcpy (str + strlen (str), "Something");
for example. 例如。
I agree with others: strcat()
should be faster. 我同意其他人:
strcat()
应该更快。 But for "best-practice", if you really care about speed, you should use neither. 但对于“最佳实践”,如果你真的关心速度,你就不应该使用。 You'd better have a struct like:
你最好有一个像这样的结构:
typedef struct { size_t len, max; char *str; } mystring_t;
to keep track of the end of the string. 跟踪字符串的结尾。 When you append a string, simply jump to the end and copy it.
附加字符串时,只需跳到最后并复制即可。 Double
max
if the allocated memory is not large enough. 双
max
如果分配的内存不够大。 Alternatively, you may have something a bit fancy by packing len
, max
and str
together. 或者,通过将
len
, max
和str
打包在一起,您可能会有点想象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.