Shame, Java string concatenation yet there are so many gestures!

Brother, my sophomore year, to see your share of "Ali Baba Java Development Manual," a piece of content, said:. "Loop body, string concatenation is best to use StringBuilder append method instead of the + operator" in the end why ah, I usually have to use the '+' sign operator ah! Brother can have time to write an article analyze it?

Just yesterday, a reader called micro-channel side dishes I said above paragraph.

My first feeling was to see this micro letter is: you too dishes dish it, I do not know why ah! I guess're reading this article, you will feel the same way.

But ask yourself, in the first two years I worked as a programmer, I do not know why. Encountered string concatenation on the "+" sign operator, no matter is not in the loop body. And side dishes than up, I was so lucky he did not, there is an enthusiastic "brother" to share in the development of this manual priceless.

Since I am so enthusiastic about sharing, it is better to do good in the end, right? I was in earnest to write an article to doubts about the side dishes.

01, the "+" operator

Gesture to say, the "+" is the string concatenation operator must most commonly used, and not one.

String chenmo = "沉默";
String wanger = "王二";
System.out.println(chenmo + wanger);
复制代码

We use this code JAD decompile it.

String chenmo = "\u6C89\u9ED8"; // 沉默
String wanger = "\u738B\u4E8C"; // 王二
System.out.println((new StringBuilder(String.valueOf(chenmo))).append(wanger).toString());
复制代码

I went to the original compile time to a "+" operator to replace the append method has become a StringBuilder. That is, the "+" sign in the string concatenation operator when just a formalism that allows developers to use relatively simple, the code looks relatively simple, relatively smooth read. Java is considered a syntactic sugar it.

02、StringBuilder

Removing the "+" operator, StringBuilder the second common method is to append a string of splicing the gesture.

First look at the source code append method of the StringBuilder class:

public StringBuilder append(String str) {
    super.append(str);
    return this;
}
复制代码

These three lines of code nothing to see, to see that the append method of the parent class AbstractStringBuilder:

public AbstractStringBuilder append(String str) {
    if (str == null) {
        return appendNull();
    }
    int len = str.length();
    ensureCapacityInternal(count + len);
    str.getChars(0, len, value, count);
    count += len;
    return this;
}
复制代码

String 1) Analyzing the splice is not null, and if so, as a character string "null" to handle.

Method source appendNull follows:

private AbstractStringBuilder appendNull() {
    int c = count;
    ensureCapacityInternal(c + 4);
    final char[] value = this.value;
    value[c++] = 'n';
    value[c++] = 'u';
    value[c++] = 'l';
    value[c++] = 'l';
    count = c;
    return this;
}
复制代码

2) after the length character array splicing exceeds the current value exceeds, for expansion and replication.

Method source ensureCapacityInternal follows:

private void ensureCapacityInternal(int minimumCapacity) {
    // overflow-conscious code
    if (minimumCapacity - value.length > 0) {
        value = Arrays.copyOf(value,
        newCapacity(minimumCapacity));
    }
}
复制代码

3) Copy the string str spliced ​​to the target value in the array.

str.getChars(0, len, value, count)
复制代码

03、StringBuffer

After the first, there StringBuilder StringBuffer, like two twins twins, the others have, but more than big brother breathing StringBuffer because two of fresh air, so is thread-safe.

public synchronized StringBuffer append(String str) {
    toStringCache = null;
    super.append(str);
    return this;
}
复制代码

StringBuffer class append method more than one keyword synchronized StringBuilder, you can ignore the toStringCache = null.

Lian Shu is a very easy synchronized keyword in Java, is a synchronous lock. It modified method is called synchronization method is thread-safe.

04, concat method of the String class

Alone on the posture of view, concat method of the String class just like append StringBuilder class.

String chenmo = "沉默";
String wanger = "王二";

System.out.println(chenmo.concat(wanger));
复制代码

I wrote this article, I suddenly had a wonderful idea. If there are two such lines of code:

chenmo += wanger
chenmo = chenmo.concat(wanger)
复制代码

How much of a difference between them?

We have previously learned, chenmo + = wanger is actually equivalent to (new StringBuilder (String.valueOf (chenmo))). Append (wanger) .toString ().

To explore the difference between the "+" sign and concat operator, in fact, depends on the difference between the method and append concat method.

We analyzed the source code before the append method. We look at the source code concat method of it.

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);
}
复制代码

1) If the length of the string is spliced ​​0, then return the string before splicing.

if (otherLen == 0) {
    return this;
}
复制代码

2) to buf array variable value string of the original character array.

char buf[] = Arrays.copyOf(value, len + otherLen);
复制代码

3) Copy the string str spliced ​​to the character array buf and returns the new string object.

str.getChars(buf, len);
return new String(buf, true);
复制代码

By roughly source code analysis we can draw the following conclusions:

1) If the string is spliced ​​null, concat time throws NullPointerException, "+" number operator would be as "null" strings to handle.

2) If the stitching string is an empty string ( ""), then the efficiency concat to be a little higher. After all, does not require new StringBuilder object.

3) If the stitching string very much, concat efficiency will drop, because the more string object is created, the greater the cost.

Attention! ! !

Weak weak to ask ah, there are students with JSP do? EL expression is not allowed "+" to the string concatenation operator, only this time using the concat.

${chenmo.concat('-').concat(wanger)}
复制代码

05, join method of the String class

JDK 1.8 provides a new string concatenation posture: String class adds a static method join.

String chenmo = "沉默";
String wanger = "王二";
String cmower = String.join("", chenmo, wanger);
System.out.println(cmower);
复制代码

The first parameter is the string concatenation operator, for example:

String message = String.join("-", "王二", "太特么", "有趣了");
复制代码

The output is: king - Tete it - interesting

Let's look at the source code join method:

public static String join(CharSequence delimiter, CharSequence... elements) {
    Objects.requireNonNull(delimiter);
    Objects.requireNonNull(elements);
    // Number of elements not likely worth Arrays.stream overhead.
    StringJoiner joiner = new StringJoiner(delimiter);
    for (CharSequence cs: elements) {
        joiner.add(cs);
    }
    return joiner.toString();
}
复制代码

I discovered a new class StringJoiner, class name looks 6, to read and very easy to read. StringJoiner is a class java.util package, for constructing a sequence of characters by the delimiter reconnected. Due to space limitations, we do not do too much description, and interested students can go to find out.

06、StringUtils.join

Real items which, when we deal with strings, often use this class --org.apache.commons.lang3.StringUtils, join the class method is a new posture of string concatenation.

String chenmo = "沉默";
String wanger = "王二";

StringUtils.join(chenmo, wanger);
复制代码

This method is more adept at the array of string concatenation, and do not worry NullPointerException.

StringUtils.join(null) = null
StringUtils.join([]) = ""
StringUtils.join([null]) = ""
StringUtils.join(["a", "b", "c"]) = "abc"
StringUtils.join([null, "", "a"]) = "a"
复制代码

By looking at the source code, we can see its internal use is still StringBuilder.

public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
    if (array == null) {
        return null;
    }
    if (separator == null) {
        separator = EMPTY;
    }

    final StringBuilder buf = new StringBuilder(noOfItems * 16);

    for (int i = startIndex; i < endIndex; i++) {
        if (i > startIndex) {
            buf.append(separator);
        }
        if (array[i] != null) {
            buf.append(array[i]);
        }
    }
    return buf.toString();
}
复制代码

I read this, invariably there is such a feeling: I rely on (sound to prolong), did not think ah did not expect, string concatenation a full six kinds of gestures ah, come home at night be sure to try out the next.

07, to answer a side dish

I believe, side dishes read my article, he will understand why Alibaba does not recommend using the "+" operator in a for loop stitching a string.

Look at two pieces of code.

The first stage, for loop using a "+" operator.

String result = "";
for (int i = 0; i < 100000; i++) {
    result += "六六六";
}
复制代码

Second paragraph, for cycle use append.

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
    sb.append("六六六");
}
复制代码

It took more than two pieces of code are long would it? On my iMac out of the test results are:

1) executing the first code is 6212 milliseconds time

2) End of the second paragraph of code execution time of 1 millisecond

The gap is too big special What of it! why?

I believe that many students already have their own answer: the first for loop created a lot of StringBuilder object, and the second piece of code start to finish only a StringBuilder object.

版权声明:本文为CSDN博主「沉默王二」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qing_gee/article/details/103060599
复制代码

Top Content:

1, " Historical Introduction to the article classification list! Featured are excellent blog here! "

2, the Spring after the start of the Boot optimization exactly how soon?

3, the Spring often committed ten errors, which pits you stepped on it?

4, do not say "distributed transaction" theory, directly on the manufacturers solutions, absolutely practical!

5, Alibaba programmers commonly used 15 of developer tools! You know a few?

6, around seven open source Spring Boot end of the separation project, be sure to buy it!

7, with Git and Github efficiency 10 Tips!

8, vigilance, MyBatis's size () method as many pit!

9, the interviewer: thread of execution order, so many answers you could not answer?

10, taught you mess code refactoring

[Video] welfare 2T free learning videos, search or scan the two-dimensional code micro-channel public concern number: Java back-end technology (ID: JavaITWork), and 20 million people with learning Java! Re: 1024 to access our FREE! Contains SSM, Spring family bucket, micro-services, MySQL, MyCat, clusters, distributed, middleware, Linux, network, multi-threaded, Jenkins, Nexus, Docker, ELK and so free learning videos, continuously updated!

Guess you like

Origin juejin.im/post/5dd3d8256fb9a01feb77ff8f