Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Как пишут в документации, StringBuilder — безопасно применять в многопоточных приложениях, но второй более эффективен.
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String s1 = "s1";
String s2 = "s2";
String s3 = "s3";
System.out.println("-----------------");
String res1 = s1 + s2;
System.out.println(res1);
System.out.println("-----------------");
String res2 = s1 + s2 + s3;
System.out.println(res2);
System.out.println("-----------------");
String res3 = s1;
res3 += s2;
System.out.println(res3);
System.out.println("-----------------");
String res4 = s1;
res4 += s2 + s3;
System.out.println(res4);
}
}
* This source code was highlighted with Source Code Highlighter.public class Test
{
public Test()
{
}
public static void main(String args[])
{
String s1 = "s1";
String s2 = "s2";
String s3 = "s3";
System.out.println("-----------------");
String res1 = (new StringBuilder(String.valueOf(s1))).append(s2).toString();
System.out.println(res1);
System.out.println("-----------------");
String res2 = (new StringBuilder(String.valueOf(s1))).append(s2).append(s3).toString();
System.out.println(res2);
System.out.println("-----------------");
String res3 = s1;
res3 = (new StringBuilder(String.valueOf(res3))).append(s2).toString();
System.out.println(res3);
System.out.println("-----------------");
String res4 = s1;
res4 = (new StringBuilder(String.valueOf(res4))).append(s2).append(s3).toString();
System.out.println(res4);
}
}
* This source code was highlighted with Source Code Highlighter.Просто хотелось показать, что даже с дефолтным конструктором StringBuilder/StringBuffer работают значительно быстрее.Имхо, это очевидно должно быть даже для джуниоров ) Ну, или хотя бы для тех, кто хотя бы образно представляет, как работаю строки в Java и что из себя представляет конкатенация строк. Выше показали, что работает через StringBuilder. Кстати, именно поэтому всё описанное относится только к конкатенации в цикле и совсем не имеет отношения к линейной конкатенации, типа String s = " bla " + bla() + " bla " + ..., на которой никакого смысла делать через StringBuilder.append нету, ибо оно так и делается, только выглядит короче и писать удобнее.
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}
buff = buff.concat(word).concat(" ");
public final class StringBuilder extends AbstractStringBuilder
...
public StringBuilder append(String str) {
super.append(str);
return this;
}
public final class StringBuffer extends AbstractStringBuilder
...
public synchronized StringBuffer append(String str) {
super.append(str);
return this;
}
public class Sandbox {
static interface Array {
void append(Object o);
}
static class ArrayListArray implements Array {
List<Object> contents = new ArrayList<Object>();
@Override
public void append(Object o) {
contents.add(o);
}
}
static class SimpleArray implements Array {
int size = 0;
Object[] contents = new Object[16];
@Override
public void append(Object o) {
if (contents.length - 1 == size) {
Object[] newContents = new Object[contents.length * 2];
System.arraycopy(contents, 0, newContents, 0, contents.length);
contents = newContents;
}
contents[size++] = o;
}
}
private static void measure(Runnable r) {
long start = System.currentTimeMillis();
r.run();
System.out.println("current = " + (System.currentTimeMillis() - start));
}
private static void measureArray(final Array a) {
measure(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
a.append("aaaa" + i);
}
}
});
}
public static void main(String[] args) {
measureArray(new ArrayListArray());
measureArray(new SimpleArray());
}
}
String st = «Маша»;
st += «Саша»;
Создаст новый объект содержащий строку «МашаСаша» а исходные объекты будут уничтожены сборщиком мусора.
Если операций конкатенации над одним и тем же строковым объектом производится много, это приводит к интенсивному процессу порождения новых объектов и добавляет работы сборщику мусора.
for (String t : strList) {
s += t;
}
Строковые классы Java. Сравнение производительности