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