c - custom memstr (strstr) speed optimisation -


i writing routine find string within specified block of memory in embedded (arm cortex m0 @16mhz) application , wondering why 2 different versions have written run @ different speeds.

char* memstr(char* mem, uint32_t n, char* str) {      if( (str[0] == '\0') || (n == 0) )   return null;      uint32_t = 0;     char* max_mem;      max_mem = mem + n;      while( mem < max_mem ) {         if( *mem != str[i] ) {             mem -= i;             = 0;         } else {             if(str[i+1] == '\0')   return mem - i;             i++;         }         mem++;     }      return null; }   char* memstr2(char* mem, uint32_t n, char* str) {      if( (str[0] == '\0') || (n == 0) )   return null;      uint32_t c = 0;     uint32_t = 0;      while( c < n ) {         if( mem[c] != str[i] ) {             c -= i;             = 0;         } else {             i++;             if(str[i] == '\0')   return &mem[c - + 1];         }         c++;     }      return null; } 

memstr consistently 1us faster memstr2 when finding 7 character string in between 20 , 200 bytes of memory. example finding 7 character string in 110 bytes, memstr takes 106us , memstr2 takes 107us. 1us may not sound big deal in embedded application every tick matters it's drawback.

kind of bonus question: prompted me write own strstr faster stock strstr (e.g. finding 7 character string in 207 character string takes my_strstr 236us , strstr 274us). what's wrong though strstr must pretty optimised?

char* my_strstr(char* str1, char* str2) {     uint32_t = 0;      if( str2[0] == '\0' )   return null;      while( *str1 != '\0' ) {         if( *str1 != str2[i] ) {             str1 -= i;             = 0;         } else {             i++;             if(str2[i] == '\0')   return (str1 - - 1);         }         str1++;     }      return null; } 

first, both functions don't work if search string starting 2 equal characters: if search xxabcde , string contains xxxabcde when notice that of xxabcde doesn't match third x, have skipped 2 x's , won't match string.

you don't check whether search empty string, in case code produces undefined behaviour.

you compare memory memory. can awful lot of work comparing memory single character. if search "abcde", first have find letter a. i'd check empty string first, read first character. , first loop check character.

char first = str2 [0]; if (first == '\0') return mem;  (; mem < maxmem; ++mem) if (*mem == first) {     ... check whether there match } 

you should check data. write different code if expect search string come vs. if expect not there @ all.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -