Is using string.length() in loop efficient?

前端 未结 6 1911
我在风中等你
我在风中等你 2021-02-20 09:11

For example, assuming a string s is this:

for(int x = 0; x < s.length(); x++)

better than this?:

int length         


        
6条回答
  •  别那么骄傲
    2021-02-20 09:58

    It depends on your C++ implementation / library, the only way to be sure is to benchmark it. However, it's effectively certain that the second version will never be slower than the first, so if you don't modify the string within the loop it's a sensible optimisation to make.

提交回复
热议问题