It has already been widely known from a long time ago (* around Java 1.5) that "string concatenation is not" + ", but using StringBuffer speeds up processing". Therefore, I still basically use StringBuffer and StringBuilder for string concatenation, but I suddenly wondered "How fast is the processing speed of the concat method of the String class?", So this time, these processing speeds I tried to compare.
StringTest.java
public class StringTest {
public static void main(String[] args) {
plus();
concat();
builder();
buffer();
}
public static void plus() {
long start = System.currentTimeMillis();
String txt = "abc";
for (int i=0; i<100000; i++) {
txt += "abc";
}
long end = System.currentTimeMillis();
System.out.println("+:" + (end - start) + "ms");
}
public static void concat() {
long start = System.currentTimeMillis();
String txt = "abc";
for (int i=0; i<100000; i++) {
txt = txt.concat("abc");
}
long end = System.currentTimeMillis();
System.out.println("concat:" + (end - start) + "ms");
}
public static void builder() {
long start = System.currentTimeMillis();
StringBuilder sb = new StringBuilder("abc");
for (int i=0; i<100000; i++) {
sb.append("abc");
}
String txt = sb.toString();
long end = System.currentTimeMillis();
System.out.println("StringBuilder:" + (end - start) + "ms");
}
public static void buffer() {
long start = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("abc");
for (int i=0; i<100000; i++) {
sb.append("abc");
}
String txt = sb.toString();
long end = System.currentTimeMillis();
System.out.println("StringBuffer:" + (end - start) + "ms");
}
}
Processing content | processing time |
---|---|
+Combined by | 7439ms |
String.concat()Combined by | 2990ms |
Join with StringBuilder | 2ms |
Join by StringBuffer | 4ms |
String.concat()
String.class excerpt
//Source obtained using the Eclipse Class Decompiler plugin.
public final class String implements Serializable, Comparable<String>, CharSequence {
private final char[] value;
public String concat(String arg0) {
int arg1 = arg0.length();
if(arg1 == 0) {
return this;
} else {
int arg2 = this.value.length;
char[] arg3 = Arrays.copyOf(this.value, arg2 + arg1);
arg0.getChars(arg3, arg2);
return new String(arg3, true);
}
}
void getChars(char[] arg0, int arg1) {
System.arraycopy(this.value, 0, arg0, arg1, this.value.length);
}
}
The Java language provides special support for string concatenation operators (+) and other object-to-string conversions. String concatenation is implemented using the StringBuilder (or StringBuffer) class and its append method.
Recommended Posts