Many people who study java know that Java programmers can’t do without repeatedly knocking code! Continuously optimize the code, which means to further improve the efficiency of code operation. So, what are the details of code optimization? Let Xiaoqian give you a brief explanation, hoping to help students who want to master java knowledge!
1. Try to specify the final modifier of class and method
Classes with the final modifier are not derivable. In the Java core API, there are many examples of applying final, such as Java. Lang. string. The whole class is final. Specifying the final modifier for a class can prevent the class from being inherited, and specifying the final modifier for a method can prevent the method from being overridden. If a class is specified as final, all methods of the class are final. The java compiler will look for opportunities to inline all final methods. Www.sangpi.com inline plays an important role in improving the efficiency of Java. See Java runtime optimization for details. This can improve performance by 50% on average.
2. Reuse objects as much as possible
Especially for the use of string object, StringBuilder / StringBuffer should be used instead of string connection. Because Java virtual machine takes time not only to generate objects, but also to garbage collect and process these objects in the future, generating too many objects will have a great impact on the performance of the program.
3. Use local variables whenever possible
The parameters passed when calling the method and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables and instance variables, are created in the heap, which is slower. In addition, the variables created in the stack will disappear with the end of the method, and no extra garbage collection is required.
4. Close the flow in time
In the process of Java programming, we must be careful when we operate the database connection and I / O stream. After using it, we should close it in time to release resources. Because the operation of these large objects will cause large system overhead, a little carelessness will lead to serious consequences.
5. Use synchronization code block instead of synchronization method
This point has been made very clear in the article “synchronized lock method block” in the multithreading module. Unless it can be determined that the whole method needs to be synchronized, the synchronized code block should be used as far as possible to avoid synchronizing the code that does not need to be synchronized, which affects the code execution efficiency.
In a word, Java, as the “big brother” of programming language, is constantly updated with the development of the times. Since we want to enter Java, we must remember to constantly enrich ourselves, improve our ability, and make ourselves become Java programmers more in line with the needs of the times.