Home > Mobile >  Is it faster to use strlen() than just check for null character in a for loop?
Is it faster to use strlen() than just check for null character in a for loop?

Time:08-25

I've only been able to find two posts related to this topic. In one post, the code in question was written such that strlen() was called in every iteration of the loop, which many users pointed out would cause the loop to be much slower but didn't discuss the case in which you store the result of strlen() in a variable and then use it in the condition of the loop. In the other post, (Godbolt.org

CodePudding user response:

I am hoping OP does not take away the best thing to do with the sample code posted above as to always code one way or another.

A slightly changed case results in 2 different functionalities, depending of pre-computation of string length or not.


Consider code like the below with s pointing to an n-length string.

void foo1(char *s, char *p) {
  int magLen = strlen(s);
  for (int i = 0; i < magLen;   i) {
    *p   = 0;
  }
}

void foo2(char *s, char *p) {
  for (int i = 0; s[i];   i) {
    *p   = 0;
  }
}

void foo3(char * restrict s, char * restrict p) {
  for (int i = 0; s[i];   i) {
    *p   = 0;
  }
}

foo1() and foo3() iterates n times.

foo2() may iterate up to n times. In foo1() and foo2(), the compiler cannot assume the string pointed to by s, and the string pointed to by p do not overlap. With foo1(), it makes no difference. With foo2(), the loop may stop early due to a new null character appearing in s the string.

Moral of the story: code for correct functionality before worrying about efficiency.

  • Related