String three brothers in Java

Source: Internet
Author: User

When writing Java programs, we often need to splice some strings, we often use "+" to splice, but in Java if we directly use this method of stitching, we will create a lot of string type object, so that, The system will have a large impact on server objects and systems performance due to the excessive number of string objects. So there's a better way to stitch strings in Java: Using StringBuffer or StringBuilder.

A, string and StringBuffer

String: is an immutable class, and any change to a string will result in a new string object.

When we use string to stitch two strings, we can execute the following lines of code:

<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >string a = "123"; String B = "456"; String C = A + b;</span>

The concatenation of this string is: 123456. And when the program is finished, we will find that in order to meet the needs of the program execution, the system establishes a,b,c three objects in the execution process. That is, when you use String's "+" method to stitch strings, there are many new objects of type String that are used to meet the needs of program invocation and execution. Therefore, when too many objects are created, the performance and execution efficiency of the system is affected.

StringBuffer: mutable class, any change to the string it refers to does not produce a new object .

Use StringBuffer to perform the operation of two string additions:

<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >    stringbuffer sb1 = new StringBuffer (str1);    Sb1.append (STR2);    String result1 = sb1.tostring ();</span>

When this process is complete, all we need is the RESULT1 object, and the SB1 that occurs in the middle of the execution process is already the target of garbage collection. This not only avoids the multiple string objects that are created during execution, but also reduces the CPU utilization.

At this point, if we want to implement SB1,SB2,SB3 three string concatenation, we just need to continue execution on the basis of the above, we can:

<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >stringbuffer SB2 = new StringBuffer (RESULT1); Sb2.append (STR3); String result2 = sb2.tostring ();</span>

Thus, what is useful to us is only the Result2 object, where the generated SB2 and RESULT1 have become the target of system recycling. If you continue to increase the number of strings, the system will generate several StringBuffer and string garbage objects accordingly.

While Java garbage is the first to occupy memory, and then Java Virtual opportunity to garbage collection of the thread to reclaim the garbage, so that there will be CPU loss, colleagues these garbage object generation will also incur overhead, so if you use the string "+" in a loop, The resulting overhead will be non-negligible and incalculable.

But with respect to StringBuffer for string connections,

<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >stringbuffer sb = new StringBuffer (); Sb.append (str1); Sb.append (str2); Sb.append (StrN); String result = sb.tostring ();</span>

Remove the middle of a StringBuffer object will eventually be discarded, the others are valid objects, compared to the above generated a pair of garbage, improve the efficiency is not stint.

Ii. StringBuffer and StringBuilder

StringBuffer

StringBuffer: String variable (Synchronized, thread safe). If you want to modify the string content frequently, it is best to use stringbuffer for efficiency reasons, and if you want to turn to string type, you can call the ToString () method of StringBuffer.

The main operations on the StringBuffer are append and insert methods.

StringBuilder

StringBuilder: String variable (non-thread safe). Internally, the StringBuilder object is treated as a variable-length array that contains a sequence of characters. Java.lang.StringBuilder is a variable sequence of characters that is JDK5.0 new. This class provides an API that is compatible with StringBuffer, but does not guarantee synchronization. This class is designed to be used as a simple replacement for stringbuffer, which is common when a string buffer is used by a single thread.

comparison :

In most cases, for execution speed, StringBuilder > StringBuffer. Because the former does not need to consider thread safety issues.

three or three advantages and disadvantages of the brothers  

The main performance difference between string types and StringBuffer: string is an immutable object, so each time a string is changed, a new string object is generated and the pointer is pointed to the new string object. Therefore, it is best not to use string to change the content of the strings, because each generation of the object will have an impact on the system performance, especially when there is no reference object in memory, the JVM's GC will start to work, and will be degraded.

When using the StringBuffer class , the StringBuffer object itself is manipulated each time, instead of generating new objects and changing the object references. So in most cases it is recommended to use StringBuffer, especially if the string object is often changed .

In some special cases, string object concatenation is actually compiled by Java Compiler to StringBuffer object splicing, so the speed of the string object is not slower than StringBuffer object, for example:

<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >string S1 = "This was only a" + "simple" + "test";  StringBuffer Sb = new StringBuilder ("This was only a"). Append ("simple"). Append ("test");  </span>

The speed of generating a String S1 object is no slower than stringbuffer. In fact, in Java compiler, the following conversions are done automatically:

Java compiler directly compiles the first statement above to:

<span style= "FONT-FAMILY:FANGSONG_GB2312;FONT-SIZE:18PX;" >string S1 = "This was only a simple test";  </span>

So fast. However, it is important to note that if the concatenation of strings from another string object, Java compiler will not automatically convert, the speed is not so fast.

therefore , if you want to manipulate a small amount of data, use string;

Single-threaded operation of large amounts of data, using StringBuilder;

Multithreading operations large amounts of data, using StringBuffer.

String three brothers in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.