在Java中对String进行+操作的成本是多少? [英] What is the cost of + operation on a String in Java?

查看:130
本文介绍了在Java中对String进行+操作的成本是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于此for循环,是运行时间O(n)或O(n ^ 2):

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?

推荐答案

Java字符串是不可变的。每次您这样做:

Java strings are immutable. Every time you do:

s + = c;

您实际上是在说:

s =新的String(s + c);

s = new String(s + c);

新字符串(s + c)必须分配一个长度为s + 1的字符串,或者:

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

1
2
3
4
5
6
7
8
9
...
等。

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

由于Sum(1..N)==(n + 1)(n / 2),所以它是O(n ^ 2)。

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

StringBuilder具有绝对优势的情况之一。

One of the cases where StringBuilder is a definite advantage.

这篇关于在Java中对String进行+操作的成本是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆