String concatenation in Java

Once created, a string in Java is immutable.

1. The "+" operator

The "+" operator is one of the most commonly used methods for string concatenation.

Using "+", a new string will be created when strings are concatenated. If a large number of strings are concatenated, new strings will continuously appear in the string constant pool in the method area. lead to a lot of waste of memory. It puts a lot of pressure on the constant pool of Java's method area.

二、StringBuffer

Constructs a string buffer with no characters in it and an initial capacity of 16 characters.

StringBuffer stringBuffer = new StringBuffer();

The bottom layer is an array of char type. If the array of char type is full,

AbstractStringBuilder(int capacity) {
    value = new char[capacity];
}

The append method means to append. If the char type array is full, the append method will expand the array.

Briefly analyze the underlying logic of append:

  1. You can see the append method, which is to append characters of String type. Method overloading, corresponding to int, float, long, boolean and other types of append methods.
@Override
public synchronized StringBuffer append(String str) {
    
    
    toStringCache = null;
    super.append(str);
    return this;
}
  1. The append method calls the method of the parent class. We can see that there is an ensureCapasityInternal method in the method body - to ensure the internal capacity. At the bottom of it is the logic of array expansion.
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;
}

In addition, we can see that when str==null, a null string will be appended to the string at this time. As follows: [External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-gKsu1UR5-1685641177530) (string splicing in Java/image-20230419021203366.png)]

Copy the characters in this string to the destination character array: str.getChars(0, len, value, count);

  1. If we study the underlying logic of ensureCapasityInternal, we will find that it is implemented by array copying.
public static char[] copyOf(char[] original, int newLength) {
    
    
    char[] copy = new char[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

In short, the append method will automatically expand the capacity when the appended characters exceed the capacity of the array.

How to optimize the performance of StringBuffer?

When creating StringBuffer, give an initial capacity as much as possible. It is best to reduce the number of expansions of the underlying array, and estimate it to give an appropriate array capacity.

can use

StringBuffer stringBuffer = new StringBuffer(44);

extension:

Why String string, using "+" will create a new string instead of using the previous string?

The bottom layer of String is also a char array, but it is decorated with fina.

/** The value is used for character storage. */
private final char value[];

But the underlying char array of StringBuffer is not decorated with final.

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

Related methods of StringBuffer

3. String Builder

The use is similar to StringBuffer, and the methods inside are also similar.

Difference: The method of StringBuilder is not thread-safe;

​ The methods of StringBuffer are decorated with the synchronized keyword and are thread-safe.

Guess you like

Origin blog.csdn.net/qq_43867812/article/details/130998907