Strings are one of the most commonly used data structures in Java programs, and string concatenation is often used. There are several ways to concatenate strings in Java, such as using “+” to concatenate two strings directly, the Append () method of StringBuilder, and the concat() method of String. Today, we compare the execution speed of these methods and analyze why.
Test code:
public class TestMain { public static void main(String[] args){ String str1 = "str"; long start1 = System.currentTimeMillis(); for(int i=0; i<500000; i++){ str1 += "a"; } long end1 = System.currentTimeMillis(); System.out.println("+ execution time "+(end1-start1)+" milliseconds "); System.out.println(); String str2 = "str"; long start2 = System.currentTimeMillis(); for(int i=0; i<500000; i++){ str2.concat("a"); } long end2 = System.currentTimeMillis(); System.out.println("concat execution time "+(end2-start2)+" milliseconds "); System.out.println(); StringBuilder str3 =new StringBuilder("str2:"); long start3 = System.currentTimeMillis(); for(int i=0; i<500000; i++){ str3.append("a"); } long end3 = System.currentTimeMillis(); System.out.println("append execution time "+(end3-start3)+" milliseconds "); }}Copy the code
Execution Result:
It is clear from the results that the “+” concatenation is much less efficient than the concat() and append() methods. Why is that? The “+” method concatenates strings essentially by calling the Append () method of StringBuilder, which returns strings via the toString() method, But it calls new StringBuilder().append(STR).toString(), which means we did a “+” concatenation 500,000 times, It just new the StringBuilder object 500,000 times and calls the toString() method 500,000 times to convert it to a string, which is the main reason for the time.
Let’s look at the source implementations of the append() and concat() methods:
public AbstractStringBuilder append(StringBuffer sb) { if (sb == null) return appendNull(); int len = sb.length(); // Expand ensureCapacityInternal(count + len); Sb.getchars (0, len, value, count); count += len; return this; }... public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); str.getChars(buf, len); return new String(buf, true); }Copy the code
The append() and concat() methods are efficient because they both lengthen and copy character arrays without producing any objects.
However, it is not necessary to use the “+” method in all cases. In actual development, we often have a string or two concatenation. In this case, it is recommended to use the “+” method, at least it is more consistent with people’s reading habits, the code is also concise. Instead, use the append() method when doing a lot of string concatenation.
* Like a small partner move small hands, little attention. Follow the official wechat account [programmer Mark Chou] to get more advanced Java architecture materials (“Spring Cloud micro services practice“”Deep analysis of Spring source code“”In-depth understanding of Apache Dubbo and combat“”Practice guide for front-line architects“”25 topics Java Interview Questions Manual“”Java surface by“…) .