Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the optimization skills of Java performance?

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the optimization skills of Java performance". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the optimization skills of Java performance".

1. Object generation and resizing.

A common problem in JAVA programming is that it does not make good use of the functions provided by Java language itself, which often generates a large number of objects (or instances). Because the system not only takes time to generate objects, it may also take time to garbage collect and process these objects in the future. Therefore, generating too many objects will have a great impact on the performance of the program.

Example 1: about String, StringBuffer,+ and append

The JAVA language provides operations on variables of type String. However, if it is not used properly, it will affect the performance of the program. Such as the following statement:

String name=new String ("HuangWeiFeng"); System.out.println (name+ "is my name")

It seems to be very concise, but in fact it is not. To generate binary code, perform the following steps and operations.

(1) generate a new string new String (STR_1)

(2) copy the string.

(3) load the string constant "HuangWeiFeng" (STR_2)

(4) the Constructor that invokes the string

(5) Save the string to the array (starting with position 0)

(6) get static out variables from java.io.PrintStream class

(7) generate a new string buffer variable new StringBuffer (STR_BUF_1)

(8) copy the string buffer variable

(9) A Constructor that invokes string buffering

(10) Save the string to the array (starting at position 1)

(11) call the append method in the string buffer (StringBuffer) class with STR_1 as an argument.

(12) load the string constant "is my name" (STR_3)

(13) call the append method in the string buffer (StringBuffer) class with STR_3 as an argument.

(14) execute the toString command for STR_BUF_1.

(15) call the println method in the out variable to output the result.

As you can see, these two simple lines of code generate five object variables, STR_1,STR_2,STR_3,STR_4 and STR_BUF_ 1. Instances of these generated classes are typically stored in the heap. The heap initializes the superclasses and instances of all classes, while calling the class and the constructor of each superclass. These operations consume system resources very much. Therefore, it is absolutely necessary to restrict the generation of objects.

After modification, the above code can be replaced with the following code.

StringBuffer name=new StringBuffer ("HuangWeiFeng"); System.out.println (name.append ("is my name.") .toString ()

The system will do the following.

(1) generate a new string buffer variable new StringBuffer (STR_BUF_1)

(2) copy the string buffer variable

(3) load the string constant "HuangWeiFeng" (STR_1)

(4) A Constructor that invokes string buffering

(5) Save the string to the array (starting with position 1)

(6) get static out variables from java.io.PrintStream class

(7) load STR_BUF_1

(8) load the string constant "is my name" (STR_2)

(9) call the append method in the string buffer (StringBuffer) instance with STR_2 as the parameter.

(10) execute the toString command for STR_BUF_1. (STR_3)

(11) call the println method in the out variable to output the result.

From this, we can see that the improved code only generates four object variables: STR_1,STR_2,STR_3 and STR_BUF_1. You may think that generating one less object will not greatly improve the performance of the program. But snippet 2 below will execute twice as fast as snippet 1. Because snippet 1 generates eight objects, while snippet 2 generates only four objects.

Code snippet 1:

String name= new StringBuffer ("HuangWeiFeng"); name+= "is my"; name+= "name"

Code snippet 2:

StringBuffer name=new StringBuffer ("HuangWeiFeng"); name.append ("is my"); name.append ("name.") .toString ()

Therefore, making full use of the library functions provided by JAVA to optimize the program is very important to improve the performance of JAVA programs. The main points for attention are as follows.

(1) use static variables (Static Class Variables) whenever possible

If a variable in a class does not change with its instance, it can be defined as a static variable so that all its instances share the variable.

Example:

Public class foo {SomeObject so=new SomeObject ();}

It can be defined as:

Public class foo {static SomeObject so=new SomeObject ();}

(2) do not make too many changes to the generated objects.

For some classes (such as the String class), you would rather regenerate a new object instance than modify the already generated object instance.

Example:

String name= "Huang"; name= "Wei"; name= "Feng"

The above code generates three object instances of type String. The first two will need the system for garbage collection immediately. If you want to concatenate strings, the performance will be even worse. Because the system will not be able to generate more temporary variables for this. As shown in example 1 above.

(3) when generating an object, it should be allocated a reasonable space and size.

Many classes in JAVA have their default space allocation size. For the StringBuffer class, the default allocated space size is 16 characters. If the space size for using StringBuffer in your program is not 16 characters, you must initialize it correctly.

(4) avoid generating objects or variables that are less used or have a short life cycle.

In this case, an object buffer pool should be defined. It is much less expensive to manage an object buffer pool than to generate and recycle objects frequently.

(5) initialization is only carried out within the scope of the object.

JAVA allows objects to be defined and initialized anywhere in the code. In this way, initialization can be done only within the scope of the object. So as to save the cost of the system.

Example:

SomeObject so=new SomeObject (); If (xylene: 1) then {Foo=so.getXX ();} can be modified to: if (xylene: 1) then {SomeObject so=new SomeObject (); Foo=so.getXX ();}

2. Exception (Exceptions)

Try/catch is provided in JAVA language to facilitate users to catch exceptions and handle them. However, if it is not used properly, it will also affect the performance of JAVA programs. Therefore, we should pay attention to the following two points.

(1) avoid using try/catch for application logic

If you can handle it with logical statements such as if,while, try not to use try/ catch statements as much as possible

(2) reuse exceptions

When exception handling is necessary, reuse existing exception objects as much as possible. It is thought that in exception handling, it takes most of the time to generate an exception object.

3. Thread (Threading)

Threads are generally used in a high-performance application. Because threads can make full use of the resources of the system. The program can continue to process and run while other threads are waiting for the hard disk or network to read and write. However, improper use of threads will also affect the performance of the program.

Example 2: correct use of Vector class

Vector is mainly used to store various types of objects (including the same type and different types of objects). However, in some cases, use will have an impact on the performance of the program. This is mainly determined by two characteristics of the Vector class. * Vector provides thread security protection. Even though many methods in the Vector class are synchronized. But if you have confirmed that your application is single-threaded, the synchronization of these methods is completely unnecessary. Second, when Vector looks up various stored objects, it often takes a lot of time to match the types. When these objects are of the same type, these matches are completely unnecessary. Therefore, it is necessary to design a single-threaded class or collection that holds specific types of objects to replace the Vector class. The program to replace is as follows (StringVector.java):

Public class StringVector {private String [] data; private int count; public StringVector () {this (10); / default size is 10} public StringVector (int initialSize) {data = new String [initialSize];} public void add (String str) {/ / ignore null strings if (str = = null) {return;} ensureCapacity (count+ 1); data [count++] = str;} private void ensureCapacity (int minCapacity) {int oldCapacity = data.length If (minCapacity > oldCapacity) {String oldData [] = data; int newCapacity = oldCapacity * 2; data = new String [newCapacity]; System.arraycopy (oldData, 0, data, 0, count);} public void remove (String str) {if (str = = null) {return / / ignore null str} for (int I = 0; I

< count; i++) { // check for a match if(data[i].equals(str)) { System.arraycopy(data,i+1,data,i,count-1); // copy data // allow previously valid array element be gc'd data[--count] = null; return; } } } public final String getStringAt(int index) { if(index < 0) { return null; } else if(index >

Count) {return null; / / index is > # strings} else {return data [index] / / index is good}} / * * StringVector.java * / therefore, Code: Vector Strings=new Vecto Thank you for your reading, this is the content of "what are the optimization techniques for Java performance?" after the study of this article I believe that we have a deeper understanding of the optimization skills of Java performance, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report