sprintf()被设计用来处理远不止字符串的内容,strcat()是专门为此而设。但我怀疑你正在为小事烦恼。C语言字符串在基本上是低效的,这使得这两种方法之间的差异微不足道。请读Joel Spolsky的《回到基础》以了解更多细节。
这是一个C++通常比C表现更好的实例。对于重量级字符串处理,使用std::string可能更有效,并且肯定更安全。
[编辑]
[第二次编辑]修正了代码(C字符串实现中迭代次数过多),时间和结论相应改变
我对Andrew Bainbridge的评论感到惊讶,他没有发布完整的测试代码。我修改了他的代码(自动计时)并添加了一个std::string测试。测试是在VC++ 2008(本机代码)默认的“Release”选项下(即优化)进行的,Athlon双核2.6GHz。结果:
C string handling = 0.023000 seconds
sprintf = 0.313000 seconds
std::string = 0.500000 seconds
所以在这里,strcat()明显更快(根据编译器和选项的不同,结果可能会有所不同),尽管C字符串约定本身存在效率低下的问题,并且支持我的原始建议:sprintf()携带了很多不必要的负担。然而,它仍然是最不易读和安全的,因此当性能不是关键因素时,我认为它没有太大的价值。
我还测试了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;
}
std::string
知道自己的长度,但对于编译时常量字符串字面值可能无法进行优化) - Peter Cordes