"37" String,stringbuffer,stringbuilder Differences and concepts

Source: Internet
Author: User

The basic concept:


The view API discovers that the string, StringBuffer, StringBuilder all implement the Charsequence interface, which is implemented internally with a char array, although they are all related to strings, but have different processing mechanisms.

String

String: Is an immutable amount, that is, after creation, you cannot modify the string class to be the final class, and you cannot inherit it. The best way to reuse a string type is to combine rather than inherit.
Value is a final decorated array object, so it can only be said that he can no longer refer to other objects and that the contents of the object he refers to cannot be changed. But continue to look at the source code will find that the string class does not give the two member variables any method so we can not modify the contents of the referenced object, so once the string object is created, the variable can not be modified after initialization, so that the string object is immutable object.

StringBuffer

StringBuffer: is a variable string sequence that, like string, holds an ordered string sequence (an array of type char) in memory, and a different point is that the value of the StringBuffer object is mutable.
The main operations on StringBuffer are the Append and insert methods, which can be overloaded to accept arbitrary types of data. Each method effectively converts the given data into a string, and then appends or inserts the character of the string into the string buffer. The Append method always adds these characters to the end of the buffer, while the Insert method adds characters at the specified point.

StringBuilder

StringBuilder: Basically the same as the StringBuffer class, is a variable character string sequence, the difference is StringBuffer is thread-safe, StringBuilder is thread insecure.
Java.lang.StringBuilder A variable sequence of characters is new in JAVA 5.0. This class provides an API that is compatible with StringBuffer, but does not guarantee synchronization, so the usage scenario is single-threaded. 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. If possible, it is recommended that this class be preferred because, in most implementations, it is faster than StringBuffer. The use of the two methods is basically the same.

Usage Scenarios

Scenarios using the String class: You can use the string class in scenes where the string does not change frequently, such as the declaration of a constant, a small number of variable operations.

Scenarios using the StringBuffer class: With frequent string operations (such as stitching, replacing, deleting, etc.) and running in a multithreaded environment, consider using StringBuffer, such as XML parsing, HTTP parameter parsing, and encapsulation.

Use the StringBuilder class scenario: With frequent string operations (such as stitching, replacing, and deleting) and running in a single-threaded environment, consider using StringBuilder, such as the Assembly of SQL statements, JSON encapsulation, and so on.

Parsing: Memory allocation for string

There are two types of string object creation in Java, one for literal form

String str = "Lianjia";

The other is to use the new standard method of constructing objects,

String str = new String ("Lianjia");

Both of these methods are often used in code, especially in the literal way.
However, there are some differences in performance and memory consumption between the two implementations.
It all started with the JVM. In order to reduce the duplication of string objects, it maintains a special memory, which is a string constant pool or string literal pool.

Working principle

When a string object is created in the literal form of the code, the JVM first checks the literal,
If a reference to a string object of the same content exists in the string constant pool, the reference is returned,
Otherwise, the new string object is created, then the reference is placed in a string constant pool and returned.

Literal form

String str1 = "Lianjia";

The JVM detects this literal, and here we think there is no content for the Lianjia object to exist.
This string object is created by the JVM that does not find a string object of content Lianjia through a string constant pool.
The reference to the object you just created is then put into the string constant pool, and the reference is returned to the variable str1.

String str2 = "Lianjia";

The same JVM still detects this literal, and the JVM finds the string constant pool,
The discovery content exists as a "Lianjia" string object, so a reference to the already existing string object is returned to the variable str2.
Note that new string objects are not recreated here.

Verify that str1 and str2 point to the same object, which you can pass through this code

System.out.println (str1 = = str2); True

Create with new

String str3 = new String ("Lianjia");

When we use new to construct a string object, a new string object is created, regardless of the reference to the object with the same content in the string constant pool.

System.out.println (str1 = = STR3); False, two variables point to a different object

For more information about constant pools, please Google "Java class file structure constant pool" and other keywords.

Efficiency analysis:

In terms of performance, because the operation of the string class is to produce a new string object, and StringBuilder and StringBuffer are just the expansion of a character array, the string class operates much slower than StringBuffer and STRINGB Uilder.

Briefly, the main performance difference between the string type and the StringBuffer type is that the string is an immutable object, so each time a change is made to the string type it is equivalent to generating a new string object and then pointing the pointer to the new Strin G object. Therefore, it is best not to use string to change the content of the strings, because each generation of objects 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, the speed will be quite slow.

If you use the StringBuffer class, the result will be different, and each result will operate on the StringBuffer object itself, instead of generating a new object and changing the object reference. So in general we recommend the use of StringBuffer, especially if the string object is constantly changing.

In some special cases, string object concatenation is actually interpreted by the JVM as a concatenation of StringBuffer objects, so the speed of a string object is not slower than the StringBuffer object, especially in the following string object generation, Stri NG efficiency is far faster than StringBuffer:

String S1 = "This was only a" + "simple" + "test";
StringBuffer Sb = new StringBuilder ("This was only a"). Append ("simple"). Append ("test");
You'll be surprised to find that the speed at which the String S1 object is generated is simply too fast, and at this point the stringbuffer is not at all dominant at all. In fact, this is a JVM trick, in the JVM's eyes, this

String S1 = "This was only a" + "simple" + "test";
is actually:

String S1 = "This was only a simple test";
So of course it doesn't take much time. But it is important to note that if your string is from another string object, the speed is not so fast, for example:

1 String S2 = "This was only a";
2 String S3 = "simple";
3 String S4 = "Test";
4 String S1 = S2 +s3 + S4;
At this point the JVM will behave in its original way.

Welcome to the group: public number It face questions summary discussion group

If the scan does not go in, add me (rdst6029930) pull you. You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:


http://my.csdn.net/u010321471

"37" String,stringbuffer,stringbuilder Differences and concepts

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.