Is using strlen() in the loop condition slower than just checking for the null character?

前端 未结 8 787
鱼传尺愫
鱼传尺愫 2020-12-07 00:39

I have read that use of strlen is more expensive than such testing like this:

We have a string x 100 characters long.

I think that<

8条回答
  •  爱一瞬间的悲伤
    2020-12-07 01:24

    Of course the first one will take longer than the second. They don't actually do the same thing at all--the first one is calculating the length of the string each time; the second one is (effectively) doing it only once.

    The first version is equivalent to this:

    for (int i=0; x[i] != 0; i++)
      for (int j=0; j

    Maybe you meant to say "is it more efficient to call a library strlen() than to implement my own?" The answer to that is, of course, "it depends". Your compiler may have intrinsic versions of strlen() that are optimized beyond what you would expect from source, you may be on a platform on which function calls are expensive (rare nowadays), etc.

    The only answer that's both general and correct is "profile and find out".

提交回复
热议问题