|
-
Jul 26th, 2008, 06:46 PM
#1
Thread Starter
New Member
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;
}
Last edited by A_S_I_lepy; Jul 26th, 2008 at 08:20 PM.
-
Jul 27th, 2008, 05:54 AM
#2
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.
I don't live here any more.
-
Jul 27th, 2008, 09:53 AM
#3
Thread Starter
New Member
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|