background

String concatenation is used frequently both in business and when writing algorithms. There are many ways to concatenate strings in Java. What are the differences between them and which works best for different businesses?

Underlying Principle of String

When discussing String concatenation, you first need to understand the underlying principles of strings.

We will only discuss the jdk1.8 situation here, look at the structure

private final byte[] value;
Copy the code

This one line of code says a lot. A string is essentially an immutable array of bytes. Because it’s immutable, concatenating it concatenating it actually generates multiple objects, which is why concatenating strings is discouraged. But immutable has many benefits, such as thread-safety, the possibility of a string buffer pool to reuse strings, and so on.

Method of splicing

Classic but sometimes inelegant +

String a = "123";
String b = "456";
String c = a + b;
Copy the code

The string C is the concatenated string ab, “123456.”

The code decompiled from this code is

String c = (new StringBuilder()).append(a).append(b).toString();
​
Copy the code

As you can see, this + is Java syntactic sugar, and it’s actually a StringBuilder call, concatenated with append(). We’ll talk more about StringBuilder later, but let’s talk about the pros and cons of this use first.

advantages

“+”, the biggest advantage is concise. If two strings need to be concatenated, the + sign is definitely the best way to use it.

disadvantages

There’s a lot to say about faults. Simplicity is also his biggest weakness, which is not flexible enough.

Business a

I have a string List, I need to concatenate them, what do I do?

for(String tmp:list){
    s += tmp;
}
Copy the code

A concise batch, but he hides a big problem!

This concatenation is actually done through the StringBuilder append method. You don’t need to know how it works, you just need to know that every time you loop, it’s going to create a new StringBuilder object. Object creation is expensive, if the List has thousands of thousands, memory and time overhead is unacceptable!

So Alibaba’s code says:

The surface is recommended, in fact is prohibited. Writing algorithms will consume a lot of time, resulting in failure, and the business will also increase gratuitous overhead because of this way, which is the code that leaders want to kill.

Business 2

Hello, everyone, my name is XX, I am a big X student from XXX school, my hobby is XXX.

A classic template, I need to replace the middle XXX as the controller parameter, how to do?

String s = "hello, everyone, my name is "+name+" I'm from "+school+" school big "+num+" Student, my hobby is "+ aihao;Copy the code

Belongs to usable but extremely ugly code. If other interfaces also need this template, do I need to copy this paragraph to all locations? If I’m going to change this, do I have to change everything.

The universal StringBuilder

Let’s start with the StringBuilder principle. It makes sense to think of string concatenations as arrays, and StringBuilder is a little bit like ArrayList, mutable arrays.

    /**
     * The value is used for character storage.
     */
    char[] value;
Copy the code

The difference is that there is no final decoration, and capacity expansion is performed when the threshold is reached. The append method is just going to insert backwards.

Then you can solve the problem of business one above.

StringBuilder sb = new StringBuilder();
for(String tmp:list){
    sb.append(tmp);
}
String s = sb.tostring();
Copy the code

In contrast, only one StringBuilder object is created, reducing the overhead of loop creation.

Thread safe StringBuffer

StringBuffer has the thread-safe advantage over StringBuilder by locking it. This results in a slightly lower efficiency than StringBuilder.

Flexible String. Format ()

This is technically called formatting, but it can also be used for concatenation.

Those of you who are familiar with C should be able to understand it. Let me give you an example

String MSG = String. Format (" I'm a student in %s elementary school, I love %s "," sunshine "," shit "); I am a student of Sunshine Primary School. I like to eat shitCopy the code

Use string chains instead of %s to generate the required string. Not only can you concatenate strings, you can see the following picture (stolen picture, not all verified, wrong don’t find me)

This approach solves the problem of business two. Use the String. Format () concatenation when you use it.

A little green concat

The reason why he is green is that I have not yet found what advantages he has.

String s = "123".concat("456"); // The result is equivalent to String s = "123" + "456";Copy the code

The concat method copies the previous contents of the array and writes the new contents, similar to the StringBuilder method.

But compared with the “+” sign, it is neither convenient nor efficient. There is a slight efficiency advantage in looping string concatenation conditions, but this is not allowed at all, so concat is weak.

JDK1.8 elegant writing method

The solution just mentioned for business 1 can be solved using the plain StringBuilder, but is a little verbose for business code.

Jdk1.8 gives an elegant answer

String s = String.join("_", list);
Copy the code

In one line of code, you can concatenate the strings in the list with an “_”.

The classic Guava

Guava is a good friend of our CRUD programmers, so no need to say much here. The most common ones we’ve seen are guava’s local caching and string manipulation.

String result = Joiner.on(",").join(list);
Copy the code

It’s a simple sentence, but it has a few other features than the NATIVE JDK string methods. For example, null arrays can be skipped or replaced, etc. It’s a bit more functional than the JDK. In normal Web projects, Guava is basically a dependency, which is very convenient to use.

conclusion

This article focuses on code writing, how to write concise and efficient code, is what we want to pursue. Just don’t let your junk code disgust your coworkers.