Java program performance optimization: code optimization

Source: Internet
Author: User
Tags finally block

Java program performance optimization: code optimization
Now the processing performance of the computer is getting better and better. In addition to the optimization of some code by the JDK upgrade, the Code layer may not be able to adjust some details, but I think the performance will be significantly improved during development, more importantly, we can maintain a performance-first awareness, which makes sense for some students who have been coding for a short time. In a loop, complex expressions should be avoided in both the loop body and the judgment condition to reduce repeated calculation of variables. 1. complex expressions should be avoided in the loop. In a loop, the loop condition is calculated repeatedly. Avoid placing some calculations in the loop, and the program will run faster. For example: for (int I = 0; I <list. size (); I ++) can be changed to // on my computer. The test order is 10 ^ 7, and the speed is doubled. For (int I = 0, len = list. size (); I <len; I ++) 2. Better use of variable 1. use the final modifier properly. Note that the usage of the fina modifier variable or method is different. It is a good choice to use the "static final variable" format. 2. Avoid unnecessary creation as much as possible, and avoid using static variable GC at will. Generally, static variable objects do not occupy the memory, so you should use static region code properly. 3. Replace Java with the basic data type. The String object consists of three parts: char array, offset, and String length. String str = "hello"; // create a "hello" String, and the JVM character cache pool also caches this String; String str = new String ("hello ") // In addition to creating a String, the String object referenced by str also contains a char [] array at the bottom layer. The char [] array stores h, e, l, l, o 2 more efficient use of strings 1. for constant strings, use 'string' instead of 'stringbuffer', but use StringBuilder or stringbuffer to accumulate string objects. In addition, use StringBuiler with relatively good performance when a single thread or without considering thread security (single-user data center construction and multi-user buffering ). 2. the split () method supports regular expressions, which are powerful but inefficient. StringTokenzer has better performance than the split () method. If you can implement the segmentation algorithm by yourself, the performance can be optimal, but you can use StringTokenizer to ensure readability and maintainability. Verify in the Code: StringBuilder sb = new StringBuilder (); for (int I = 0; I <100000; I ++) {sb. append (I); sb. append (",");} String str = sb. toString (); Long time1 = System. currentTimeMillis (); String [] split = str. split (","); Long time2 = System. currentTimeMillis (); System. out. println (time2-time1); Long time3 = System. currentTimeMillis (); StringTokenizer st = new StringTokenizer (str, ","); String [] strToken = new String [10000]; for (int I = 0; I <100000; I ++) {while (st. hasMoreTokens () {strToken [I] = st. nextToken () ;}} Long time4 = System. currentTimeMillis (); System. out. println (time4-time2); split 10000 times on your computer, StringTokenizer is about 3 ms on average (amount, it seems that the difference is not big ). 3. Select a reasonable data structure according to thread security requirements 1. Use HashMap and ArrayList in a single thread environment as much as possible to avoid using some collection tools optimized for the multi-threaded environment. For example, avoid random use of StringBuffer, StringBuilder, HashMap (single-thread map), and HashTable (multi-thread table. 2. The system overhead of the Regional synchronization method to reduce the effect of synchronized is relatively large. Try to use the synchronized keyword wherever synchronization is really needed. 4. Select a set of tools reasonably. when using Vector, HashTable, HashMap, and other auto-expanded data structures, you can specify the initial size to view the source code of the Vector. initialCapacity and capacityIncrement are defined, it is used to specify the initial capacity and the automatic expansion size after the set is full. When the Vector is initialized, the default capacity is 10. In most cases, this capacity is insufficient and will be expanded. For example: public vector v = new vector (20); 2. Avoid using two-dimensional arrays as much as possible. The efficiency of two-dimensional arrays is relatively low, and the difference can be 10 times. In some previous data structures or algorithm questions, for example, one-dimensional arrays replace two-dimensional arrays to represent the coordinate system. Because of the time and space expenditure, subscripts and values can be used to represent the vertical and horizontal coordinates respectively. 3. use System. arraycopy () is used instead of loop replication in the control structure of array five statements. Note 1. in java, the final keyword is used to indicate that a function is an inline function. The final keyword tells the compiler that during compilation, performance improvement is considered, the compiler directly replaces the call expression of the inline function in the program with the function body of the inline function. An inline function is similar to a macro definition in C. This blog post tests the use of final optimization. Www.bkjia.com 2. in file read/write and access link operations, related resources can be released in the finally block. like the C language, if displacement can be used for multiplication and division, the displacement should be used as much as possible. If you need to multiply or divide by the n power of 2, the displacement method can be used instead, in Java, the operators are left shift, signed right shift, and unsigned right shift. The offset operator only operates on the int value. If it is not an int value, the compiler reports an error. A = a * 4; B = B/4; // you can change it to a = a <2; B = B> 2; // description: // remove 2 = Shift 1 to the right by 2 = Shift 1 to the left // remove 4 = Shift 2 to the right by 4 = Shift 2 to the left // remove 8 = Shift 3 to the right by 8 = shift left 3-digit

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.