Java performance optimization Series II-Program Optimization

Source: Internet
Author: User

Common programming optimization skills:

1. String Optimization

(1) Characteristics of the String class: immutability and optimization for the constant pool (meaning of the String. intern () method)

(2) Memory leakage of the subString method:

(3) Use the StringTokenizer or indexOf combined with the subString () function instead of the split function for string segmentation and search.

(4) use the charAt () method instead of the startWith () method.

(5) For static string or variable string connection operations, Java will thoroughly optimize the compilation, and combine the strings of multiple connection operations into a separate string during compilation, instead of generating a large number of String instances. Generate only one object.

(6) Use StringBuilder whenever possible without considering thread security.

(7) You can set an initial value for both StringBuffer and StringBuilder during initialization. The default value is 16B. If the length of a string is greater than 16 B, you need to resize the string. The expansion policy doubles the size of the original capacity, applies for memory space with the new capacity, creates a char array, copies the content in the array to the new array, and uses Arrays. copyOf () function. Therefore, if the size of StringBuilder can be evaluated in advance, These replication operations can be saved to improve the system performance.

2. List Interface

(1) differences between ArrayList and Vector: they use almost the same algorithm, and their only difference is their support for multithreading. ArrayList is insecure, while Vector is thread-safe.

(2) differences between the ArrayList and ArrayList:

| --- 1. The shortlist is implemented using a linked list. It is suitable for scenarios where data is deleted and inserted frequently, and is not suitable for random access.

| --- 2. ArrayList is implemented using arrays. It is suitable for random searches and sequential reads. It is not suitable for scenarios where data is frequently deleted or inserted.

(3) An array-based List has a capacity parameter. When the size of the elements stored in the ArrayList exceeds the existing size, the array is resized, resulting in a memory replication of the entire array. Therefore, a reasonable array size reduces the number of array resizing times to improve system performance.

(4) use the iterator and Speed Block whenever possible during list traversal.

2. Map interface:

(1) implementation principle of HashMap: In simple terms, HashMap uses the key as the hash algorithm, maps the hash value to the memory address, and directly obtains the data corresponding to the key. In HashMap, the underlying data structure uses arrays, and the memory address refers to the subscript index of the array.

(2) capacity parameters and resizing: by default, the initial capacity of hashmap is 16, and the load factor is 0.75, that is to say, when the actual capacity of hashmap reaches the initial capacity * load factor (a threshold value maintained inside hashmap), hashmap will expand. During the expansion, the entire hashmap will be traversed. Therefore, you should set a reasonable initial size and load factor to reduce the number of times the hashmap is resized.

(3) LinkedHashMap-ordered HashMap: The biggest drawback of HashMap is its unordered nature. elements stored in Hashmap do not necessarily output in the input order when traversing HashMap, instead, HashMap sets an efficient search order based on the hash algorithm. If you want to save the input order, use LinkedHashMap. LinkedHashmap adds a linked list internally to store the order of elements.

(4) The sequence list provides two types of sequence: one is the sequence of element insertion and the other is the sequence of recent accesses. Note: During the iteration process of LinkedHashMap, if it is set to sort by the last access time, that is, whenever the get () method is used to access an element, the element will be moved to the end of the linked list. However, an exception occurs at this time. Therefore, the get () operation cannot be used in the iterator when LinkedHashMap works in this mode.

(5) ConcurrentModificationException: this exception is thrown when it is modified during the collection iteration process. Therefore, do not modify the structure of the set in the iterator mode. This feature is suitable for all collection classes, including HashMap, Vector, and ArrayList.

(6) TreeMap -- if you want to sort elements, you can use TreeMap to customize the key sorting in two ways: inject a Comparator into the TreeMap constructor or use a key that implements Comparable.

(7) If you need to add the sorting function to HashMap, it is best to use Treemap instead of customizing the sorting in the application.

(8) HashMap is implemented based on the Hash table and TreeMap is implemented based on the red and black trees.

3. Relationship between Map and Set:

(1) All Set implementations are only an encapsulation of the corresponding Map, and a Map object is maintained internally. That is, Set is only a special case of the corresponding Map Value.

(2) There are three main implementation classes of Set: HashSet, LinkedHashSet, and TreeSet. HashSet is a fast Hash-Based Element insertion, with unordered elements. LinkedHashSet maintains the element insertion sequence at the same time. When traversing a set, it is always sorted in the first-in-first-out order. TreeSet is implemented based on the red and black trees and has an Efficient Sorting Algorithm Based on element keys.

4. optimized the set access code:

(1) code that is repeatedly called in the separation loop: for example, if the size () function of the set is used in the for loop, the call of this function should not be placed in the loop, it is placed outside the loop,

(2) omit the same operation:

5. RandomAccess interface: You can use RandomAccess to check whether List supports random and fast access. At the same time, if the application needs to perform random access to the List through index subscript, try to buyaoshiyongLinkedList, ArrayList or Vector.

6. Features of JavaNIO:

1. Buffer support for all original types.

2. Use Java. nio. charset. Charset as the character encoding and decoding solution.

3. Add channel abstraction to replace the original IO stream abstraction.

4. Supports file access interfaces for lock and memory ing files.

5. Provides Selector-based Asynchronous Network I/O.

7. Use NIO in Java. A Channel is a two-way Channel that can be read or written. The application cannot directly operate the Channel, and the Buffer must be used. For example, when reading data, you must read the data from the channel to the buffer zone and then read it in the buffer zone. Taking file reading as an example, first obtain the file channel through the file input stream, then read the content of the file channel into the buffer zone, and then you can operate on the buffer zone.

8. Basic principles of Buffer:

1. Buffer creation: the static allocate (int size) method of the Buffer or Buffer. wrap (byte [] src ).

2. Buffer Working principle: three variables: position, which represents the current Buffer location. When writing a Buffer, data is written from the next position of position. Capacity indicates the upper limit of the buffer Capacity. The actual upper Limit of the buffer. That is to say, when reading data, the data is the data from position to limit.

3. flip operation: limit = position, position = 0, which is generally used during read/write switching. After writing the data, you must limit the valid data range to read the data;

4. clear operation: position-0, limit = capacity .. Prepare for re-writing the buffer.

5. rewind operation: position = 0 to prepare for reading valid data in the buffer zone. Half of the limit has been properly set.

9. read/write buffer:

1. public byte get (): read one byte of the buffer in sequence. position will add one

2. public Buffer get (byte [] dst): Read the data in the Buffer into the array dst and move the position appropriately.

3. public byte get (int index): get the nth index byte, but do not move the posoiion

4. public ByteBuffer put (byte B): put byte B into the buffer and move the position

5. public ByteBuffer put (int index, byte B): Place byte B in the index position of the buffer.

6. pubglic final ByteBuffer (byte [] src): place the byte array src in the buffer.

10. Sign Buffer: similar to a bookmarkdonefile function, the current position can be recorded at any time during data processing. Then return to this position at any time. Mark is used to record the current location, and reset is used to restore to the location where mark is located,

11. Replication Buffer: the duplicate method of the Buffer can be used to copy a Buffer. The copy Buffer shares a space with the original Buffer but has independent position, capacity, and limit values.

20. Buffer shard: the slice method is used to implement the buffer shard. It will create a sub-buffer in the existing buffer zone. The sub-buffer and the parent buffer share data. This method helps to modularize the system. A buffer shard can be used to split a large buffer. The obtained sub-buffers have a buffer model structure. This operation facilitates system modularization.

12. Read-Only Buffer: the read-only buffer can ensure the security of the core data. If you do not want data to be tampered with at will, it is very helpful to return a read-only buffer.

13. File ing to memory: NIO provides a method to map files to memory for IO operations, which is much faster than stream-based IO. This operation is mainly performed by FileChanne. map. The file memory method is used to map text to the memory through FileChannel. Then read data from the memory. At the same time, modify the Buffer to write the changes to the data in the memory to the corresponding hard disk file.

14. Processing structured data: Scattering and aggregation. Scattering is to read data into a group of bytebuffer, and aggregation is the opposite. ScatteringByteChannel and GatheringByteChannel can simplify the operations on structural data.

15. Direct Memory Access: DirectBuffer is directly allocated to the physical memory, which does not occupy space and therefore is not restricted by space. The read and write operations of DirectBuffer are better than normal Buffer blocks, because DirectBuffer directly controls the kernel Buffer.

16. Reference Type: four reference types: Strong, soft, ruo, and virtual.

WeakHashMap: a typical application of weak references. It uses weak references as a storage solution for internal data. It can be used as a simple cache table solution.

If a large Map table is required in the system, the table items in the Map are used as cache. This also means that even if the corresponding data is not obtained from the Map, the system can also obtain the data through the option scheme, although this will consume more time, but it does not affect the normal operation of the system. In this case, WeakHashMap is the most suitable. Because WeakHashMap stores all table items within the system memory range, and once the memory is insufficient, those that are not referenced during GC will be quickly cleared to avoid system memory overflow.

17. tips to help improve system performance:

1. Use exceptions with caution: Using try-catch in a for Loop will greatly reduce system performance.

2. Use local variables: the access speed of local variables is much higher than the access speed of static variables of the class, because class variables exist in the heap space.

3. bitwise operations replace multiplication and division: right shift means dividing by two, and left shift means multiplying by two.

4. Sometimes, consider whether Arrays can be used to replace bitwise operations.

5. A one-dimensional array replaces a two-dimensional array.

6. Extract expressions: make the program do less repetitive calculations as much as possible. Pay special attention to the Code in the loop body. Extracting repeated code from the loop extraction can effectively improve the system performance.

Reference books:

Java program performance optimization-Make your Java program more fragmented and more stable Ge yiming

Effctive java version 2

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.