Is using string.length() in loop efficient?

前端 未结 6 1923
我在风中等你
我在风中等你 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:56

    It depends on the inlining and optimization abilities of the compiler. Generally, the second variant will most likely be faster (better: it will be either faster or as fast as the first snippet, but almost never slower).

    However, in most cases it doesn't matter, so people tend to prefer the first variant for its shortness.

提交回复
热议问题