Tips to help improve performance

Source: Internet
Author: User

1. Caution With exceptions

In Java software development, Try-catch are often used for error trapping, but Try-catch statements are very bad for system performance. Therefore, you should try to avoid applying it in the loop.

2. Using Local variables

The parameters passed when the method is called and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables, instance variables, and so on, are created in the heap and are slower.

3. Bit operation instead of multiplication method

In all operations, bit operations are the most efficient. Therefore, we can try to use bit operation instead of some arithmetic operation to improve the operation speed of the system. The most typical is the multiplication algorithm for integer optimization.

4. Replace switch

The keyword switch statement is used for multi-conditional judgments, and the switch statement functions similarly to the IF-ELSE statement, with the same performance. Therefore, you cannot say that the switch statement degrades the performance of the system. However, in most cases, the switch statement has a performance-enhancing space.

Take a look at the following example:

        intRe = 0;  for(inti=0;i<10000000;i++) {Re=Switchint (i); }        protected intSwitchint (intz) {            inti = z%10 + 1; Switch(i) { Case1:return3;  Case2:return6;  Case3:return7;  Case4:return8;  Case5:return10;  Case6:return16;  Case7:return18;  Case8:return44; default:return-1; }        }

In the above example, the switch mode is not performing poorly in terms of branching logic. However, if you replace switch with a new idea, and realize the same program function, there will be a lot of room for improvement in performance. The following code implements the same functionality as the previous switch statement:

        intRe = 0; int[] SW =New int[]{0, 3, 6, 7, 8, 10, 16, 18, 44};//Alternative Switch Logic         for(inti=0;i<10000000;i++) {Re=Arrayint (SW, i); }        protected intArrayint (int[] SW,intz) {            inti = z%10 + 1; if(i<1| | I&GT;8)//simulate Switch's default                return-1; Else                returnSw[i]; }

The above code takes a new approach, using a sequential array instead of a switch statement. Because the random access of the array is very fast, at least better than the switch's score judgment, so it must be faster than the original implementation. By experiment, the use of switch statements is relatively time consuming 80ms, while the implementation of using arrays is only relatively time consuming 62ms.

5. One-dimensional arrays instead of two-dimensional arrays

Since the random access performance of the array is very good, many JDK class libraries, such as ArrayList, vectors, and so on, use arrays as their underlying implementations. However, as a software developer, it is also important to know that one-dimensional arrays and two-dimensional arrays have different access speeds. One-dimensional arrays have better access speed than two-dimensional arrays. Therefore, in a performance-sensitive system to use a two-dimensional array, you can try to pass a reliable algorithm, the two-dimensional array into a one-dimensional array and then processed to improve the system's response speed.

6. Extracting An expression

In the process of software development, it is easy for programmers to intentionally and unintentionally let the code do some "repetitive work", in most cases, because of the high-speed operation of the computer, these "repetitive work" does not pose a large threat to performance, but if you want to achieve the ultimate system, extracting these "repetitive work" is quite meaningful. As much as possible to make the program less repetitive calculations, especially in the loop body code, extracting duplicate code from the loop body can effectively improve system performance.

7. Expand Loops

Slightly different from the optimization techniques described earlier, the unwinding cycle is an optimization that is used in extreme situations, because the expansion loops are likely to affect the readability and maintainability of the code, which is also extremely important for software systems. However, when the performance problem becomes the main contradiction of the system, the expansion cycle is definitely a technique worth trying.

A common loop code is as follows:

int New int [9999999];          for (int i=0;i<9999999;i++) {            = i;        }

After the loop is expanded, it resembles the following format:

        int New int [9999999];          for (int i=0;i<9999999;i + = 3)            {= i;            Array[i+1] = i+1;            Array[i+2] = i+2;        }

The above two pieces of code are functionally identical, but the second section of the code is optimized for loop expansion, and the 3 loop logic in the original code snippet is processed in a loop body. Run the above two pieces of code, the first code is relatively time-consuming 94ms, the second code is relatively time-consuming 31ms, the expansion cycle can be seen, reduce the number of cycles, to improve system performance is very helpful.

8. Boolean operations instead of bitwise operations

Although bit operations are much faster than arithmetic operations, using bitwise operations instead of Boolean operations is a very bad choice when it comes to conditional judgment. Because Java makes a fairly good optimization of Boolean operations when conditions are judged. In the calculation of a Boolean expression, as long as the value of the expression can be determined, it is returned immediately, and the calculation of the remaining subexpression is skipped. If the bitwise operation (bitwise AND, bitwise, OR) is used instead of logic and logic or, although the bit operation itself has no problem, the bitwise operation always calculates all the sub-expressions and then gives the final result. Therefore, from this point of view, the use of bitwise operations instead of Boolean operations will make the system a lot of useless computation.

9. Using Arraycopy ()

Array replication is a highly used feature, and the JDK provides an efficient API to implement it:

 Public Static native void int int int length);

The System.arraycopy () function is a native function, usually the performance of the native function is superior to the normal function, and for performance reasons, the native function should be called whenever possible in software development.

10. Using buffer for I/O operations

In addition to NIO, there are two basic ways of using Java for I/O operations:

    1. Using InputStream and OutputStream-based methods
    2. Using writer and reader

Regardless of the way you use the file I/O, the performance of I/O can be improved effectively if buffering is used properly.

11. Use Clone () instead of new

The most common way to create new object instances in Java is to use the New keyword. The JDK supports the New keyword very well and is very fast when creating lightweight objects with the new keyword. However, for heavyweight objects, the execution time of the constructor may be longer because the object may perform some complex and time-consuming operations in the constructor. This results in a long time-consuming creation of objects, and also makes it impossible for the system to obtain a large number of instances in a short period of time. To solve this problem, you can use the Object.clone () method.

The Object.clone () method can quickly replicate an object instance by bypassing the object constructor. Because you do not need to call an object constructor, the Clone () method is not affected by the performance of the constructor and can be used to quickly generate an instance. However, by default, the Clone () method generates an instance that is only a shallow copy of the original object. If deep copies are required, the clone () method needs to be re-implemented.

12. Static method Substitution instance method

The method that uses the keyword static declaration is a static method. In Java, because the instance method needs to maintain a structure similar to the virtual function table, the support for polymorphism is realized. The invocation of an instance method requires more resources than a static method. Therefore, for some commonly used tool class methods, there is no need to overload them, then you can declare them as static to speed up the invocation of the method.

Tips to help improve 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.