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

How to optimize Java programming and coding to improve performance

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

Share

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

This article introduces you how to optimize Java programming and coding to improve performance, the content is very detailed, interested friends can refer to, hope to be helpful to you.

By using some auxiliary tools to find the bottleneck in the program, and then you can optimize the bottleneck part of the code. There are generally two options: optimizing the code or changing the design method. We generally choose the latter, because not calling the following code will improve the performance of the program better than calling some optimized code. A well-designed program can simplify the code and improve performance.

Here are some methods and techniques that are often used in the design and coding of JAVA programs in order to improve the performance of JAVA programs.

First, the generation and resizing of objects.

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 the parameter

(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 the parameter

(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 (STR_3) for STR_BUF_1

(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 a string, the performance will be even worse because the system will not have to generate more temporary variables for this, as shown in example 1 above.

(3) when generating an object, it should be allocated 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 (Xerox 1) then {Foo=so.getXX ();}

Can be modified to:

If (Xerox 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, do not 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.

III. Threads (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 programs used to replace are 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}

Therefore, the code:

Vector Strings=new Vector (); Strings.add ("One"); Strings.add ("Two"); String Second= (String) Strings.elementAt (1)

You can replace it with the following code:

StringVector Strings=new StringVector (); Strings.add ("One"); Strings.add ("Two"); String Second=Strings.getStringAt (1)

In this way, you can improve the performance of JAVA programs by optimizing threads. The programs used for testing are as follows

(TestCollection.java):

Import java.util.Vector; public class TestCollection {public static void main (String args []) {TestCollection collect = new TestCollection (); if (args.length = = 0) {System.out.println ("Usage: java TestCollection [vector | stringvector]"); System.exit (1);} if (args [0] .equals ("vector")) {Vector store = new Vector (); long start = System.currentTimeMillis (); for (int I = 0; I < 1000000) ITunes +) {store.addElement ("string");} long finish = System.currentTimeMillis (); System.out.println ((finish-start)); start = System.currentTimeMillis (); for (int I = 0; I < 1000000; iTunes +) {String result = (String) store.elementAt (I);} finish = System.currentTimeMillis (); System.out.println ((finish-start)) } else if (args [0] .equals ("stringvector")) {StringVector store = new StringVector (); long start = System.currentTimeMillis (); for (int I = 0; I < 1000000; iTunes +) {store.add ("string");} long finish = System.currentTimeMillis (); System.out.println ((finish-start)); start = System.currentTimeMillis (); for (int I = 0; I < 1000000; iTunes +) {String result = store.getStringAt (I) Finish = System.currentTimeMillis (); System.out.println ((finish-start));}

With regard to the operation of threads, pay attention to the following aspects:

(1) prevent excessive synchronization

As shown above, unnecessary synchronization often results in a decline in program performance. Therefore, if the program is single-threaded, do not use synchronization.

(2) synchronize the method instead of the entire code snippet

Synchronizing a method or function performs better than synchronizing an entire code snippet.

(3) use the mechanism of multiple "locks" for each object to increase concurrency.

In general, there is only one "lock" per object, which indicates that a "deadlock" occurs when two threads execute two different synchronization methods of an object. Even if the two methods do not share any resources. To avoid this problem, you can implement a "multi-lock" mechanism on an object. As follows:

Class foo {private static int var1; private static Object lock1=new Object (); private static int var2; private static Object lock2=new Object (); public static void increment1 () {synchronized (lock1) {var1++;}} public static void increment2 () {synchronized (lock2) {var2++;}

IV. Input and output (Igamo)

Input and output include many aspects, but the most involved are read and write operations to hard disk, network or database. For read and write operations, it is divided into cached and non-cached ones; for database operations, there are many types of JDBC drives to choose from. But in any case, it will affect the performance of the program. Therefore, we need to pay attention to the following points:

(1) use input / output buffering

Use caching as much as possible. However, if you want to flush the cache frequently, it is recommended that you do not use it.

(2) output stream (Output Stream) and Unicode string

When using Output Stream and Unicode strings, the Write class is more expensive. Because it needs to realize the conversion from Unicode to byte. So, if possible, implement the transformation or use the OutputStream class instead of the Writer class before using the Write class.

(3) use transient when serialization is needed

When serializing a class or object, those atomic types (atomic) or elements that can be reconstructed should be identified as transient types. This eliminates the need to serialize every time. If these serialized objects are to be transmitted over the network, this small change will greatly improve performance.

(4) use caching (Cache)

For objects or data that are often used but do not change, you can store it in a cache. In this way, the speed of access can be improved. This is especially important for result sets returned from the database.

(5) use a fast JDBC drive (Driver)

JAVA provides four ways to access the database. Two of these are JDBC drives. One is a local drive outsourced with JAVA; the other is a full JAVA drive. Which one to use depends on the environment in which JAVA is deployed and the application itself.

5. Some other experiences and skills

(1) use local variables.

(2) avoid calling functions or methods (get or set) in the same class to set or call variables.

(3) avoid generating the same variable or calling the same function in the loop (same as parameter variables).

(4) use keywords such as static,final,private as much as possible.

(5) when copying large amounts of data, use the System.arraycopy () command.

On how to optimize Java programming and coding to improve performance is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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