optimize replace function in C
hi every one-
I made a replace function in C - the function is very stable and it works, but when it comes to large data, the function takes a long time.
- is there any other way I can improve the speed of my function ??
the following is my code
Thanks in advance :)
Code:
char *_replace(char* source_str,char* search_str,char* replace_str,char* ostr , int *sz)
{
char *data = source_str;
char *orgdata = data;
char *_ostr = malloc(*sz);
int ser_sz = strlen(search_str);
int rep_sz = strlen(replace_str);
int src_sz = strlen(source_str);
int tempdata = 0;
if (rep_sz > ser_sz){
int lstr = src_sz/ser_sz;
int tst = lstr * rep_sz;
_ostr = malloc(lstr * rep_sz);
}
_ostr[0] = str_NULL; /* remove garbage value */
do{
char *p = strstr(data,search_str); /* get the pointer to the first occurrence */
if (!p){
break;
}
strncat(_ostr,orgdata,p - orgdata); /*append the rest of the string*/
data = p + ser_sz; /*ignore the search term*/
strncat(_ostr,replace_str,rep_sz); /* place the replace string*/
orgdata = p + ser_sz; /* save the current data*/
}while(1);
tempdata = strlen(orgdata);
*sz = strlen(_ostr) + 1 + tempdata;
ostr = malloc(*sz);
ostr[0] = 0;
strncpy(ostr,_ostr,*sz);
strncat(ostr,orgdata,tempdata); /*append the rest*/
free(_ostr);
*sz = *sz - 1;
return ostr;
}
Re: optimize replace function in C
- You could handle three situations in different ways...
1. search_str is shorter than replace_str.
2. search_str is the same length as replace_str.
3. search_str is longer than replace_str.
That would let you optimise each situation diferently and get speed increases when reducing the length of the string.
- Avoid using the str???() functions. Try to use memcpy() if possible or handle your char copying manually.
- use inline ASM and avoid calling functions altogether.
Depends how far you want to go with this.
Re: optimize replace function in C
I do have 2 diffrent situation in this code.
-search_str is longer than replace_str
-search_str is shoter or same as the replace_str
I do have my own inline strlen,memcpy,memcat functions - but it turned out that I am not a better programmer than ms programmers :) becasue my functions take 5 - 10 ms more than theirs. I was imporving this and a lot of other function for over 6months now so I kind of reached my limit in optimizing this function :( - guess I have to go with this. this function takes over 10min to finesh replacing all the "0;" to "le" form the string "debug_ii = 0;" repeated for 10.9mb.
thanks for the help :) - Any one else any idea ??