Optimized version of strstr (search has constant length)

后端 未结 5 1038
孤城傲影
孤城傲影 2020-12-31 08:42

My C program had a lot of strstr function calls. The standard library strstr is already fast but in my case the search string has always length of 5 characters. I replaced i

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 09:05

    Reducing the number of comparisons will increase the speed of the search. Keep a running int of the string and compare it to a fixed int for the search term. If it matches compare the last character.

    uint32_t term = ct[0] << 24 | ct[1] << 16 | ct[2] << 8 | ct[3];
    uint32_t walk = cs[0] << 24 | cs[1] << 16 | cs[2] << 8 | cs[3];
    int i = 0;
    
    do {
      if ( term == walk && ct[4] == cs[4] ) { return i; } // or return cs or 1
      walk = ( walk << 8 ) | cs[4];
      cs += 1;
      i += 1;
    } while ( cs[4] ); // assumes original cs was longer than ct
    // return failure
    

    Add checks for a short cs.

    Edit:

    Added fixes from comments. Thanks.

    This could easily be adopted to use 64 bit values. You could store cs[4] and ct[4] in local variables instead of assuming the compiler will do that for you. You could add 4 to cs and ct before the loop and use cs[0] and ct[0] in the loop.

提交回复
热议问题