Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of Java StringBuilder.substring() method? If it is linear, is there a constant time complexity method to get a substring?

In my opinion it should be constant(O(1)) time complexity. However I was told that a new String object has to be instantiated when invoking stringBuilder.substring() method. (It is not static method). If this is true, how can I get a substring within a constant time complexity?

like image 361
Yuanwei Chen Avatar asked Oct 17 '25 13:10

Yuanwei Chen


1 Answers

You cannot possibly create a String from a StringBuilder in constant time and have its immutability maintained. Additionally, as of Java 7 Update 25, even String#substring() is linear time because structural sharing actually caused more trouble than it avoided: substring of a huge string retained a reference to the huge char array.

like image 143
Marko Topolnik Avatar answered Oct 20 '25 03:10

Marko Topolnik