Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...