Java program performance optimization and java Performance Optimization

Source: Internet
Author: User

Java program performance optimization and java Performance Optimization

 

Java program tuning entry-level tutorials seem very thick. In fact, the book is very thin, domestic handwriting is high, of course there are some content suspected of plagiarism, suitable for java development experience is not enough, General Master, this type of skill is required. It took me two weeks to summarize the results as follows (excluding JVM):

 

1. Common System Bottleneck factors: disk I/O, network operations, CPU, java exception capture and processing, database read/write, lock competition, GC

2. Speed-up ratio: Speedup <= 1/(F + (1-F)/N). F indicates the proportion of serial computing, and N indicates the number of CPU logic.

3. optimization level: Design Optimization ---> code optimization ---> JVM parameter optimization ---> database optimization ---> OS optimization, when there is a bottleneck in the actual application that requires optimization, the general steps are: Code ---> JVM parameters ---> database ---> OS ---> application architecture (Design)

4. Common design optimization methods:

1: multi-purpose design mode (single instance, enjoy yuan, observer, visitor, modifier, proxy, etc)

2: Buffer/Cache, Buffer/Cache ideas

3: multi-thread parallel replacement of serial (generally there is no causal or frontend relationship between serial)

4: Application Server Load balancer (JVM-level, handling shared data consistency issues)

5: time/space conversion

6: Use ValueObject to reduce the number of computations or requests

5. Several Simple entry points for code optimization:

0): do not define references in the loop body and create objects. Put the definition references out.

Object obj = null;

For (int I = 0; I <10000; ++ I ){

 (Object)Obj = new Object ();

System. out. println ("obj =" + obj );

}

1): avoid repeated object initialization.

Public class {

Private Hashtable table = new Hashtable ();

Public (){

Table = new Hashtable (); // initialize the Hashtable object table twice.

}

}

1): String Optimization

A: The substring () method is fast, but it is prone to memory overflow. Because the reference to the original String is retained, it is recommended to use new String (***. substring (parameter) Mode

B: split can be used to intercept strings, but the StringTokenizer (not recommended by sun) can be considered for high speed. It is best to use indexOf + substring to intercept strings by yourself.

C: startsWith/endsWith is generally used for determining the start and end substrings of a string. Because they are based on regular expressions like split, it is best to use charAt to achieve faster speed.

D: Add strings. StringBuild is the best, StringBuffer is the second (thread safety), String. concat is the second, and ++ is the most (static constant Compiler optimization is not considered)

2): Comparison between ArrayList (Vector) and sorted list

A: ArrayList is based on arrays (a continuous memory space), and ArrayList is based on a two-way linked list. Therefore, the main energy consumption of ArrayList is Data Replication during extended space hours, the consumer list consumes data traversal (especially data in the middle)

B: The addition/deletion at the beginning and end has no pressure on the sequence list, but each random access needs to be searched from the beginning.

C: There is no pressure on the ArrayList to be added at the end. However, if you delete the ArrayList from the header, array replication is required.

D: traverse the vertex list by using for-Each or Iterator. Do not use normal ini I = 0; I <size; I ++ because get (I) it is a random search, and each time it is traversed from the beginning or the end, it will take a kiss

E: Generally, a class that implements the RandomAccess interface, such as ArrayList, allows the Vector to use get with ease during the time period. In addition, the time period should be minimized to obtain the size or element repeatedly, and cache it with temporary variables.

3) HashMap if the key is an object that overrides the hashCode method one by one, if the hashCode method puts the same int value back, each time it is put into a different object, it will go to the same bucket, and the traversal query is very slow

4) HashMap uses arrays at the underlying layer, and uses an exponential power greater than or equal to initialCapacity and 2 as the array size. threshold is the product of the total capacity of the current array and the load factor, that is, the threshold value, array Extension replication is performed when the actual capacity exceeds the threshold, so proper initialCapacity is conducive to improving performance.

5): LinkedHashMap sorts elements in sequence or accessed Order (the accessed elements are placed at the end), and TreeMap sorts them based on the passed Comparetor parameter or key objects that implement Comparable, the application scope is different. HashSet, LinkedHashSet, and TreeSet are simple encapsulation corresponding to Map.

6): using NIO (ByteBuffer + Channel) can increase the I/O read/write rate. Note that duplicate (), asReadOnlyBuffer (), and slice () all share the original cache data, generally, MappedByteBuffer is mapped to the file memory, ScatteringByteChannel is the structured scattering interface, and GatheringByteChannel is the structured aggregation interface. Multiple bytebuffers are written into an array at a time, using DirectBuffer instead of ByteBuffer for multiple read/write operations can improve the efficiency. However, DirectBuffer directly opens up the OS memory. If the OS memory is frequently created and recycled, the performance is inferior to the same operations in the ByteBuffer virtual machine.

7) Four reference levels: Strong, soft, weak, and virtual, which have different functions. Generally, soft and weak references can be used as a cache solution to avoid memory overflow, virtual resources are used to track the object recycling time. Weak references to WeakHashMap can be used as simple cache objects.

8): try-catch is not used in the circular code. try to put it in the circular body as much as possible. Store the calculated values with local or temporary variables to avoid repeated calculation, you can consider multiple operations in one loop to reduce the number of cycles (I + 1, I + 2, I + 3 ...), we often use "intrusive" logical operations such as & to replace bitwise operations such as & (of course, we generally do not recommend using conditional judgment for some operations, so the subsequent judgments should not be run by default)

9): replace two-dimensional arrays with one-dimensional arrays; Use Buffer for I/O; Replace new with clone for functions with high construction costs (note that Cloneable is implemented in this class, and shortest replication is used by default, the clone method of the Object needs to be rewritten for deep replication)

10): Tips: Use bitwise operations to replace the multiplication and division of 2 power; use static methods instead of instance methods; use native methods such as arrayCopy;

 

 

 

 

 

 

 

 

 

 



From Weizhi note (Wiz)



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.