strcat是C语言一个基本的字符串操作函数,它的源代码一般是这样的。
char *strcat(char *dest, const char *src)
{
char *tmp = dest;
while (*dest) dest++;
while ((*dest++ = *src++) != '\0');
return tmp;
}
由此可见,strcat调用时,先移动目标字符串的指针到其尾部,再进行复制。这种做法对于下标比较大的数组重复调用时,效率比较低。想象一下,第一次调用strcat时,指针由0数到100,只不过复制了几个字符,第二次调用strcat时,指针又从0数到108,无论调用多少次,指针总是从0数起,就会知道这个时候是多么浪费系统资源了!
我找到一个办法,字符串追加时,事先给出目标字符串结尾所在的位置,追加时,也就不用从头开始计算其长度了,复制的过程中,目标字符串的结尾也随之移动,下一次再追加也就可以使用它了。以下就是优化过的string_append,与strcat相比,增加了一个整形指针以传递目标字符串长度的地址。
/*
* optimizer for strcat when appending to a large array again and again
*/
char *string_append(char *dest, int *end, const char *src) {
if ( *end >= 0 && dest && src ) {
char *p = dest + *end;
while ( *p++ = *src++ ) (*end)++;
}
return dest;
}
经试验,string_append在大数组重复追加内容的情形下,优势非常明显。其它情形下,使用原来的strcat也就足够了。
#include <stdio.h>
#include <string.h>
#include <time.h>
#define BUFF_SIZE 4096
/*
* optimizer for strcat when appending to a large array again and again
*/
char *string_append(char *dest, int *end, const char *src) {
if ( *end >= 0 && dest && src ) {
char *p = dest + *end;
while ( *p++ = *src++ ) (*end)++;
}
return dest;
}
int main() {
int i = 0, j = 0;
int retry = 100000;
int field = 100;
char output1[BUFF_SIZE], output2[BUFF_SIZE];
time_t time1 = time(NULL);
for ( i = 0; i < retry; i++ ) {
memset(output1, 0, BUFF_SIZE);
int length = 0;
string_append(output1, &length, "header\n");
for ( j = 0; j < field; j++ ) {
string_append(output1, &length, "\tcall detail record ");
char c[8];
sprintf(c, "%d", j);
string_append(output1, &length, c);
string_append(output1, &length, "\n");
}
string_append(output1, &length, "trailer\n");
}
time_t time2 = time(NULL);
printf("It takes %d seconds to show the performance of string_append()\n", time2 - time1);
time1 = time(NULL);
for ( i = 0; i < retry; i++ ) {
memset(output2, 0, BUFF_SIZE);
strcat(output2, "header\n");
for ( j = 0; j < field; j++ ) {
strcat(output2, "\tcall detail record ");
char c[8];
sprintf(c, "%d", j);
strcat(output2, c);
strcat(output2, "\n");
}
strcat(output2, "trailer\n");
}
time2 = time(NULL);
printf("It takes %d seconds to show the performance of strcat()\n", time2 - time1);
if ( strcmp(output1, output2) )
printf("They are NOT equal\n");
else
printf("They are equal\n");
return 0;
}
-bash-3.2$ ./string_append_demo
It takes 2 seconds to show the performance of string_append()
It takes 11 seconds to show the performance of strcat()
They are equal
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/yui/archive/2010/05/22/5616455.aspx