Java improvements (13) ----- string

Source: Internet
Author: User

It can be proved that string operations are the most common behavior in computer programming.

 

I. String

First, we need to make it clear that String is not a basic data type, but an object and an immutable object. When you view the source code, you will find that the String class is of the final type (of course it cannot be inherited). By viewing the JDK documentation, you will find almost every operation to modify the String object, actually, a New String object is created.

The String is an object, so before initialization, its value is null. It is necessary to mention the differences between "", null, and new String. Null indicates that the string is not new, that is, the object reference has not been created, and no memory space is allocated to it. "", new String () indicates that it is new, it is null internally, but it creates an object reference and requires memory space allocation. For example, you can't say there is nothing in an empty glass, because there is air in it. Of course, you can also make it a vacuum, null and, new String () the difference is like vacuum and air.

There is a special place in the string, that is, the string pool. Whenever we create a String object, we first check whether there are strings with the same nominal value in the string pool. If there are strings, we will not create them. We will directly put them back to the reference of this object in the string pool, if not, it is created and put into the string pool and a reference to the new object is returned. This mechanism is very useful because it can improve efficiency and reduce memory space usage. Therefore, in the process of using strings, we recommend that you use direct value assignment (that is, String s = "aa "), create a new String object (that is, String s = new String ("aa") unless necessary ")).

The use of strings is nothing more than the following:

1. String comparison

Equals () ------ determine whether the content is the same.

CompareTo () ------ judge the size relationship of a string.

CompareToIgnoreCase (String int) ------ case insensitive during comparison.

= ------ Determine whether the content is the same as the address.

When signorecase () ------ ignore case sensitivity to determine whether the content is the same.

ReagionMatches () ------ compare whether some content in the string is the same (For details, refer to API ).

2. string SEARCH

CharAt (int index) ------ return the character at the specified index position. The index range starts from 0.

IndexOf (String str) ------ search str from the String and return the location where it first appears.-1 is not returned.

IndexOf (String str, int fromIndex); ------ retrieves str starting from the fromIndex character of the String.

LastIndexOf (String str) ------ locate the last occurrence location.

LastIndexOf (String str, int fromIndex) ---- locate the last occurrence position from the fromIndex character of the String.

StarWith (String prefix, int toffset) ----- test whether the substring starting from the specified index starts with the specified prefix.

StarWith (String prefix) ------ test whether the String starts with the specified prefix.

EndsWith (String suffix) ------ test whether the String ends with the specified suffix.

3. String Truncation

Public String subString (int beginIndex) ------ returns a new String, which is a subString of this String.

Public String subString (int beginIndex, int endIndex) ------ the returned String is the String from beginIndex to the endIndex-1.

4. String replacement

Public String replace (char oldChar, char newChar ).

Public String replace (CharSequence target, CharSequence replacement) ------ replace the original etarget subsequence with the replacement sequence and return a new String.

Public String replaceAll (String regex, String replacement) ------ use a regular expression to match strings. Note that the first parameter of replaceAll is a regular expression.

5. For more methods, refer to API

 

Ii. StringBuffer

StringBuffer and String are used to store strings, but their internal implementation methods are different, resulting in different scopes. For StringBuffer, when processing strings, if you modify it, it does not generate a new String object, so it is superior to String in terms of memory usage.

In fact, many StringBuffer methods are similar to the String class, and the functions are almost the same. However, when the StringBuffer is modified, the String class generates a new object, which is the biggest difference between them.

At the same time, StringBuffer cannot be initialized using =. It must generate a StringBuffer instance, that is, you must initialize it through its constructor.

In the use of StringBuffer, it focuses more on the changes to the string, such as append, modify, delete, the corresponding method:

1. append (): append the specified content to the end of the current StringBuffer object. Similar to the string connection, the content of the StringBuffer object will change here.

2. insert: This method inserts content into the StringBuffer object.

3. delete: This method is mainly used to remove content from the StringBuffer object.

 

III, StringBuilder

StringBuilder is also a variable String object. The difference between StringBuffer and StringBuffer is that it is thread insecure. Based on this, it is generally faster than StringBuffer. Like StringBuffer, the main operations of StringBuider are append and insert methods. Both methods can effectively convert the given data to a string, and then add or insert the character of the string to the string generator.

The above is just a brief introduction of String, StringBuffer, StringBuilder. In fact, we should focus more on the differences they only see, only by clarifying the differences between them can they be better used.

 

4. Use String, StringBuffer,StringBuilder

Let's take a look at the following table:

 

Here, I am not very clear about whether String is thread-safe. The reason is: String is not variable, and all operations cannot change its value. Is there thread-safe? However, if it is hard to say whether the thread is secure, it will always be safe because the content is immutable.

In terms of usage, because each String modification requires a new object, it is best to choose StringBuffer or StringBuilder for strings that often need to change content. for StringBuffer, each operation is performed on the StringBuffer object itself, and it does not generate new objects. Therefore, StringBuffer is particularly applicable when the string content is frequently changed.

However, not all String operations are slower than StringBuffer operations. In some special cases, String concatenation is parsed by JVM into a StringBuilder object, in this case, the String speed is faster than the StringBuffer speed. For example:

String name = "I" + "am" + "chenssy ";

StringBuffer name = new StringBuffer ("I"). append ("am"). append ("chenssy ");

For these two methods, you will find that the first one is much faster than the second one, and the advantages of StringBuffer are completely lost here. The real reason is that the JVM has been optimized. In fact, String name = "I" + "am" + "chenssy "; in the eyes of JVM, It is String name = "I am chenssy"; this method is really not necessary for JVM. However, if we add a String object to this object, the JVM will construct the String object according to the original specification.

The usage scenarios of these three methods are summarized as follows (see compiling quality code: 151 suggestions for improving java programs):

1. String: the String class can be used in scenarios where the String does not change frequently, such as the declaration of constants and a small amount of variable operations.

2. StringBuffer: The StringBuffer can be used to operate strings frequently (such as concatenation, replacement, and deletion) and run in a multi-threaded environment, for example, XML parsing, HTTP Parameter Parsing, and encapsulation.

3. StringBuilder: The StringBuffer can be used to operate strings frequently (such as concatenation, replacement, and deletion) and run in a multi-threaded environment, such as SQL statement assembly and JSON encapsulation (it seems that these two are also used | StringBuffer ).

For more information about the differences between them, see http://www.cnblogs.com/zuoxiaolong/p/lang1.html. You will not be able to draw any more.

 

V. String concatenation

For strings, we often need to assemble them. in java, we have improved three assembly methods: +, concat (), and append. What are the differences between the three? Let's take a look at the following example:

 

Public class StringTest {/*** @ desc use +, concat (), append () method cycle: 10 million times * @ author chenssy * @ data 2013-11-16 * @ param args * @ return void */public static void main (String [] args) {// + long start_01 = System. currentTimeMillis (); String a = a; for (int I = 0; I <100000; I ++) {a + = B;} long end_01 = System. currentTimeMillis (); System. out. println (+ time consumed: + (end_01-start_01) + mm); // concat () long start_02 = System. currentTimeMillis (); String c = c; for (int I = 0; I <100000; I ++) {c = c. concat (d);} long end_02 = System. currentTimeMillis (); System. out. println (the time consumed by concat: + (end_02-start_02) + mm); // append long start_03 = System. currentTimeMillis (); StringBuffer e = new StringBuffer (e); for (int I = 0; I <100000; I ++) {e. append (d);} long end_03 = System. currentTimeMillis (); System. out. println (Time consumed by append: + (end_03-start_03) + mm);} ------------ Output: + time consumed: 19080mm concat time consumed: 9089mm time consumed by append: 10mm

 

Public class StringTest {/*** @ desc use +, concat (), append () method cycle: 10 million times * @ author chenssy * @ data 2013-11-16 * @ param args * @ return void */public static void main (String [] args) {// + long start_01 = System. currentTimeMillis (); String a = a; for (int I = 0; I <100000; I ++) {a + = B;} long end_01 = System. currentTimeMillis (); System. out. println (+ time consumed: + (end_01-start_01) + mm); // concat () long start_02 = System. currentTimeMillis (); String c = c; for (int I = 0; I <100000; I ++) {c = c. concat (d);} long end_02 = System. currentTimeMillis (); System. out. println (the time consumed by concat: + (end_02-start_02) + mm); // append long start_03 = System. currentTimeMillis (); StringBuffer e = new StringBuffer (e); for (int I = 0; I <100000; I ++) {e. append (d);} long end_03 = System. currentTimeMillis (); System. out. println (Time consumed by append: + (end_03-start_03) + mm);} ------------ Output: + time consumed: 19080mm concat time consumed: 9089mm time consumed by append: 10mm
From the preceding running results, we can see that append () is the fastest, concat () is the second, and + is the slowest. For the reason, see the following breakdown:

 

(1) + concatenate strings

We know that the compiler has optimized the + method. It uses the append () method of StringBuilder for processing. We know that the speed of StringBuilder is faster than that of StringBuffer, but why is the running speed still like that? This is mainly because the compiler needs to convert the append () method to a String after append, that is, str + = "B" is equivalent

Str = new StringBuilder (str). append (B). toString ();

The key reason for its slowdown lies in the new StringBuilder () and toString (). Here, we have created 10 million StringBuilder objects, and each time we need to convert them into strings. Is the speed slow?

(2) concatenate a string using the concat () method

 

public String concat(String str) {    int otherLen = str.length();    if (otherLen == 0) {        return this;    }    char buf[] = new char[count + otherLen];    getChars(0, count, buf, 0);    str.getChars(0, otherLen, buf, count);    return new String(0, count + otherLen, buf);    }

 

This is the source code of concat (). It looks like a digital copy form. We know that the processing speed of the array is very fast, but the method is as follows: return new String (0, count + otherLen, buf); this also creates 10 million string objects, which is the root cause of its slowdown.

(3) concatenate a string using the append () method

public synchronized StringBuffer append(String str) {    super.append(str);        return this;    }

The append () method of StringBuffer directly uses the append () method of the parent class AbstractStringBuilder. The source code of this method is as follows:

 

public AbstractStringBuilder append(String str) {    if (str == null) str = null;        int len = str.length();    if (len == 0) return this;    int newCount = count + len;    if (newCount > value.length)        expandCapacity(newCount);    str.getChars(0, len, value, count);    count = newCount;    return this;    }

 

Similar to the concat () method, it also performs character array processing, lengthen, and then copy, but note that it returns itself instead of returning a new string, that is to say, during this cycle, it does not generate a new String object.

Through the above analysis, we need to select the appropriate string splicing method in the appropriate place, but it is not necessary to select the append () and concat () methods, the reason is that + according to our programming habits, only the append () and concat () methods can be used to greatly help the efficiency of our system, at the same time, I have never used the concat () method.

 

Related Article

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.