Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the programming skills for optimizing the performance of Java programs

Shulou Source: shulou.com Published: 2022-06-02 03:57:40 10月06日 Update

This article mainly explains "what are the programming skills of Java program performance optimization", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what are the programming skills of Java program performance optimization"?

1. Be cautious in using exceptions

In Java software development, try-catch is often used for error trapping, but try-catch statements are very bad for system performance. Although the loss of performance can not be detected in a try-catch, once try-catch is applied to the loop, it will bring great harm to the system performance.

The following is an example of applying try-catch to a for loop

Public void test () {int a = 0; for (int I = 0; I < 1000000; iTunes +) {try {a = a + 1; System.out.println (I);} catch (Exception e) {e.printStackTrace () }

The running time of this code is 27211 ms. If you move try-catch to extracorporeal circulation, you can improve system performance, as shown in the following code

Public void test () {int a = 0; try {for (int I = 0; I < 1000000; iTunes +) {a = a + 1; System.out.println (I);}} catch (Exception e) {e.printStackTrace ();}}

It takes 15647 ms to run. The influence of tyr-catch on system performance can be seen.

2. Use local environment

The parameters passed when the method is called and the temporary variables created in the call are stored in the Stack, which is faster. Other variables, such as static variables, instance variables, and so on, are created in the Heap and are slow.

Here is a test case

/ / private static int a = 0; public static void main (String [] args) {int a = 0; long start = System.currentTimeMillis (); for (int I = 0; I < 1000000; iTunes +) {a = a + 1; System.out.println (I);} System.out.println (System.currentTimeMillis ()-start) }

The running result is obvious: using static variables takes time 15677ms, and using local variables takes time 13509ms. Thus it can be seen that the access speed of local variables is higher than that of member variables of the class.

3. Bit operation instead of multiplication and division

Of all the operations, bit operation is the most efficient. Therefore, we can try to use bit operations instead of partial arithmetic operations to improve the running speed of the system.

For example, bit operations are used in the source code of HashMap.

Static final int DEFAULT_INITIAL_CAPACITY = 1

Tags: Methods performance operations arrays systems objects instances expressions statements speed code variables loops programs Boolean software functions copies software development static Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Docker Shulou Technology macOS MariaDB