Home  >  Article  >  Java  >  How to optimize the execution efficiency of Java code

How to optimize the execution efficiency of Java code

Guanhui
GuanhuiOriginal
2020-05-14 16:47:122338browse

How to optimize the execution efficiency of Java code

How to optimize the execution efficiency of Java code

1. Try to specify the final modifier of the class. Classes with final modifiers It is not derived;

In the Java core API, there are many examples of applying final, such as java.lang.String. Specifying final for the String class prevents people from overriding the length() method. In addition, if a class is designated as final, all methods of the class will be final. The Java compiler will look for opportunities to inline all final methods (this depends on the specific compiler implementation). This can improve performance by an average of 50%.

2. When using the synchronization mechanism, try to use method synchronization instead of code block synchronization;

The synchronization method uses the synchronized modification method. Before calling this method, you need to Obtain the built-in lock (each object in Java has a built-in lock), otherwise it will be in a blocking state

Code such as:

 public synchronized void save(){
 //内容
 }

The synchronized code block is modified with synchronized(object){}, in When calling this code block, you need to obtain the built-in lock, otherwise it will be in a blocking state

Code such as:

  synchronized(object){ 
//内容
    }

3. Do not catch exceptions in the loop;

Try {

} catch() {

}

It should be placed on the outermost layer.

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of How to optimize the execution efficiency of Java code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn