What is complexity of length() function in String class of Java?

后端 未结 4 1825
栀梦
栀梦 2021-02-20 07:53

Is it O(n) or O(1) (By saving length in a private variable during string allocation to the object).

if it is O(n), does it mean that the complexity of following code is

4条回答
  •  一整个雨季
    2021-02-20 08:25

    In Java any String is backed up by an final array. So it is simple to just return the array length. So it is O(1) complexity. And if you think in your code

    for(int i=0; i

    s.length() is called for every iteration then you are not right. Modern compiler optimizes this type of call and changes s.length() to constant number(i.e the length of the String instance).

提交回复
热议问题