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

前端 未结 8 809
鱼传尺愫
鱼传尺愫 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:23

    I guess the compiler could optimize (check Gregory Pakosz comment) your first for loop so that you would be like this:

    int len = strlen(x);
    for (int i = 0; i < len; i++)
    

    Which is still O(n).

    Anyway, I think your second for loop will be faster.

提交回复
热议问题