0

Is it bad to use 'str.length()' in a for loop or any kind of loop? Does this make O(n^2) complexity? If it is bad, we can assign it to a variable and use the variable instead, right?

Roxy
  • 132
  • 2
  • 9
  • 1
    *"Does this make O(n^2) complexity?"* - I have no idea why you'd think that. And no, it's not bad (why do you think that?) – UnholySheep Mar 16 '17 at 08:56

1 Answers1

1

No. String is immutable, and length() has O(1) complexity. Simply returns already initialised number.

https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/lang/String.java

EDIT: thanks Real Sceptic

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22