sprintf() 旨在处理的不仅仅是字符串, strcat() 是专家。但我怀疑你正在为这些小事出汗。C 字符串从根本上说是低效的,这使得这两种提议的方法之间的差异变得微不足道。阅读Joel Spolsky 的“回归基础”了解血腥细节。
这是 C++ 通常比 C 执行得更好的一个实例。对于重量级字符串处理,使用 std::string 可能更有效,当然也更安全。
[编辑]
[第 2 次编辑]更正的代码(C 字符串实现中的迭代次数过多)、时间和结论相应地改变
我对 Andrew Bainbridge 的评论感到惊讶,即 std::string 速度较慢,但他没有发布此测试用例的完整代码。我修改了他的(自动计时)并添加了一个 std::string 测试。测试是在具有默认“发布”选项(即优化)、Athlon 双核、2.6GHz 的 VC++ 2008(本机代码)上进行的。结果:
C string handling = 0.023000 seconds
sprintf = 0.313000 seconds
std::string = 0.500000 seconds
因此,尽管 C 字符串约定固有的效率低下,但 strcat() 到目前为止速度更快(您的里程可能会因编译器和选项而异),并且支持我最初的建议,即 sprintf() 携带大量不需要为此目的的包袱. 然而,它仍然是迄今为止可读性和安全性最低的,因此当性能不重要时,IMO 几乎没有什么优点。
我还测试了一个 std::stringstream 实现,它又慢了很多,但对于复杂的字符串格式仍然有优点。
更正后的代码如下:
#include <ctime>
#include <cstdio>
#include <cstring>
#include <string>
void a(char *first, char *second, char *both)
{
for (int i = 0; i != 1000000; i++)
{
strcpy(both, first);
strcat(both, " ");
strcat(both, second);
}
}
void b(char *first, char *second, char *both)
{
for (int i = 0; i != 1000000; i++)
sprintf(both, "%s %s", first, second);
}
void c(char *first, char *second, char *both)
{
std::string first_s(first) ;
std::string second_s(second) ;
std::string both_s(second) ;
for (int i = 0; i != 1000000; i++)
both_s = first_s + " " + second_s ;
}
int main(void)
{
char* first= "First";
char* second = "Second";
char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char));
clock_t start ;
start = clock() ;
a(first, second, both);
printf( "C string handling = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;
start = clock() ;
b(first, second, both);
printf( "sprintf = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;
start = clock() ;
c(first, second, both);
printf( "std::string = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;
return 0;
}