What is the cost of + operation on a String in Java?

雨燕双飞 提交于 2019-12-13 11:15:12

问题


For this for loop, is the run time O(n) or O(n^2):

char[] ar = new char[1000];
String s = "";
Arrays.fill(ar, 'a');
for(Character c: ar){
    s += c;
}

So basically, what is the run time of + on a String? How does it work behind the scene in Java?


回答1:


Java strings are immutable. Every time you do:

s+=c;

You're really saying:

s = new String(s + c);

new String(s + c) must allocate a string of length s + 1, or:

1 2 3 4 5 6 7 8 9 ... etc.

Since Sum(1..N) == (n + 1) (n / 2), this is O(n^2).

One of the cases where StringBuilder is a definite advantage.




回答2:


From "Effective Java" by Josh Bloch; Item 33 in the book:

Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic > in n...When two strings are concatenated, the contents of both are copied.

Use StringBuilder. I believe its performance is O(n).



来源:https://stackoverflow.com/questions/8530023/what-is-the-cost-of-operation-on-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!