Introduction to strings in java, optimization of strings, and efficient use of strings, java strings

Source: Internet
Author: User

Introduction to strings in java, optimization of strings, and efficient use of strings, java strings

  • Introduction 

String is the most important data type in java. String is one of the most important objects in software development. Generally, string objects occupy the largest space block in the memory. Therefore, efficient processing of strings will improve the overall system performance.

In java, the String object can be considered as a derivative and further encapsulation of the char array. Its main components are: char array, offset, and string length. The char array indicates the content of the string, which is the superset of the string represented by the string object. The real content of the String also requires the offset and length to be further located and intercepted in the char array. (Check the java source code to see the char array, offset, and length definitions)

Three basic features of a String object:

1. immutability. Once a String object is generated, it cannot be changed. This feature of the String object can be used in the constant mode, that is, the state of an object does not change after the object is created. In addition, the immutable mode is mainly used to omit the synchronization and lock wait time when an object needs to be shared by multiple threads and frequently accessed, thus greatly improving the system performance.

2. Optimization for the constant pool; when two string objects have the same value, they only reference the same copy in the constant pool. When the same string appears repeatedly, the memory space can be greatly reduced.

3. Define final of the class. The String object of the final class cannot have any subclass in the system, which protects the system security.

  StringThe following methods are used to check a single character, compare string, search string, extract substring, create a copy of string, and convert all characters to uppercase or lowercase letters, skillful Use of these methods will be of great help in enterprise development.

  • Truncates a substring.

  One of the most common operations in java is to intercept substrings. in java, two methods are provided to intercept substrings:

1 substring(int beginIndex, int endIndex)2 substring(int beginIndex)

View the source code of substring (int beginIndex, int endIndex:

1 public String substring (int beginIndex, int endIndex) {2 if (beginIndex <0) {3 throw new StringIndexOutOfBoundsException (beginIndex); 4} 5 if (endIndex> value. length) {6 throw new StringIndexOutOfBoundsException (endIndex); 7} 8 int subLen = endIndex-beginIndex; 9 if (subLen <0) {10 throw new StringIndexOutOfBoundsException (subLen ); 11} 12 return (beginIndex = 0) & (endIndex = value. l Ength ))? This13: new String (value, beginIndex, subLen); 14}View Code

At the end of the method, a new String object is returned to view its constructor:

1 public String (char value [], int offset, int count) {2 this. value = value, 3 this. offset = offset, 4 this. count = count5}View Code

In the source code, this is a constructor of the package scope. It aims to efficiently and quickly share the char array objects in the String. However, in the offset-Based String truncation method, the value array of the String native content is copied to the new substring. Imagine that if the length of a substring is short but the length of the original string is long, the truncated substring contains all the content in the native string and occupies the corresponding memory space, the actual value is determined only by the offset and length. This method increases the computing speed but wastes space. It is a solution that changes the time for space.

Instance code:

1 public class Test {2 3 public static void main (String [] args) {4 List <String> hander = new ArrayList <String> (); 5 for (int I = 0; I <100000; I ++) {6 HugeStr str = new HugeStr (); 7 // ImpHugeStr str = new ImpHugeStr (); 8 hander. add (str. getSubString (0, 5); 9} 10} 11 12} 13 14 static class ImpHugeStr {15 private String str = new String (new char [10000]); 16 public String getSubString (int begin, int end) {// capture the substring and regenerate the new String 17 return new String (str. substring (begin, end); 18} 19} 20 static class HugeStr {21 private String str = new String (new char [10000]); 22 public String getSubString (int begin, int end) {// capture the substring 23 return str. substring (begin, end); 24} 25}

ImpHugeStr uses the String constructor without memory leakage to regenerate the String object, causing the String object returned by the subString () method to lose the strong reference, this ensures the stability of the system memory.

SubString () causes memory leakage because the String (int offset, int count, char [] value) constructor is used. This constructor uses the space-for-time policy.

The above constructor is used in Java and the following constructor is used in Java:

1 public String (char value [], int offset, int count) {2 if (offset <0) {3 throw new StringIndexOutOfBoundsException (offset ); 4} 5 if (count <0) {6 throw new StringIndexOutOfBoundsException (count); 7} 8 // Note: offset or count might be near-1 >>> 1. 9 if (offset> value. length-count) {10 throw new StringIndexOutOfBoundsException (offset + count); 11} 12 this. value = Arrays. copyOfRange (value, offset, offset + count); 13}View Code

This. value = Arrays. copyOfRange (value, offset, offset + count) is used in the code to recycle the strong reference of value without memory overflow.

  • String segmentation and search

String segmentation and search are also one of the most common methods for string processing. string segmentation is to cut the original string into a small string based on a delimiter.

There are three methods to separate strings:

1. original string segmentation:

Split () is the most primitive string segmentation method, but it provides a very powerful string segmentation function. The input parameter can be a regular expression to implement string segmentation of complex logic. However, for the simple string style, the split () performance is not satisfactory. All performance-sensitive systems are not desirable.

2. Use the StringTokenizer class to split the string:

StringTokenizer is a tool class provided by JDK for separating substrings by strings.

Its constructor is new StringTokenizer (String str, String delim). The str parameter is the delimiter to be processed, and the delim parameter is the delimiter. After a StringTokenizer object is generated, you can use the nextToken () method to obtain the Next string to be separated. You can use the hasMoreTokens () method to determine whether more substrings need to be processed. For more details about StringTokenizer usage, refer to the API.

3. Separate strings by yourself:

You can use two methods of the String object: indexOf () and subString (). As mentioned above, subString () is a space-for-time policy, which runs fast and indexOf is also a very fast method.

Implementation Code:

1 String str = ""; // String to be split 2 while (true) {3 String subStr = null; 4 int j = str. indexOf (";"); // delimiter 5 if (j <0) break; 6 subStr = str. subString (0, j); // capture the subString 7 str = str. subString (j + 1); // remaining subString to be intercepted 8}

Comparison of the three methods: the first method is powerful, but the efficiency is the worst; the second method is StringTokenizer, because of split, StringTokenizer can be used as much as possible; the third method is the best in execution efficiency, but the readability is poor.

In addition, the String object also provides a charAt (int index) method, which returns the index character in the specified String. Its function is opposite to indexOf, however, the execution efficiency is also very high. For example, we often encounter a problem in the project team that determines whether a String starts with XX or ends with XX. The first thing we think of is the startWith () and endWith () methods provided by the String object. If charAt () is used () method implementation, the efficiency will be much faster. Example: "abcd ". change startWith ("abc") to "abcd ". charAt (1) = "a" & "abcd ". charAt (1) = "B" & "abcd ". charAt (1) = "c" can improve system efficiency in a large number of scenarios.

  • StringBuffer and StringBuilder

The String object is an unchangeable object. When you need to modify the string object, the string object will always generate new objects, and all the performance will be poor. Therefore, JDK provides a tool specifically used to create and modify strings, namely StringBuffer and StringBuilder.

1. Accumulative operations of String constants:

The String object is non-mutable. Therefore, once the String object instance is generated, it cannot be changed. The following code:

1 String str = "abc"+"de"+"f"+"gh";

First, the "abc" and "de" strings generate "abcde" objects, and then generate "abcdef" and "abcdefgh" objects in sequence. Theoretically, this will not be very efficient.

Use StringBuilder to implement appeal:

1 StringBuffer sb = new StringBuffer();2 ab.append("abc");3 ab.append("de");4 ab.append("f");5 ab.append("gh");

For static string connection operations, java will thoroughly optimize the compilation, and generate a separate long string for the strings of multiple connection operations during compilation, so the efficiency will be high.

2. String variable accumulation operation:

String to accumulate variable strings:

1 String str1 = "abc";2 String str2 = "de";3 String str3 = "f";4 String str4 = "gh";5 String str = str1+str2+str3+str4;

During java compilation, the string processing is optimized to some extent. For variable string accumulation, the StringBuilder object is used to accumulate strings. However, when writing code, we recommend that you use StringBuffer or StringBuilder for optimization. In addition, the efficiency of methods similar to "+ =" or "+" in java is lower than that of the concat () method of the String object, while the concat () method is much lower than that of the StringBuilder class. Therefore, StringBuilder should be used in projects to improve efficiency.

3. Selection of StringBuffer and StringBuilder

StringBuffer synchronizes almost all methods, while StringBuilder does not synchronize any data. The synchronization method consumes certain system resources. Therefore, StringBuilder is more efficient than StringBuffer. However, in a multi-threaded environment, StringBuilder cannot guarantee thread security. Therefore, StringBuilder with good performance is used without considering thread security. If the system has thread security requirements, StringBuffer is used.

In addition, both StringBuffer and StringBuilder can set the capacity.

1 void expandCapacity (int minimumCapacity) {2 int newCapacity = value. length * 2 + 2; // expand capacity 3 if (newCapacity-minimumCapacity <0) 4 newCapacity = minimumCapacity; 5 if (newCapacity <0) {6 if (minimumCapacity <0) // overflow 7 throw new OutOfMemoryError (); 8 newCapacity = Integer. MAX_VALUE; 9} 10 value = Arrays. copyOf (value, newCapacity); // array copy 11}

The size of the capacity is evaluated in advance, which can effectively reduce the array resizing operation and improve the system performance.

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.