By using auxiliary tools to find bottlenecks in your program, you can then optimize the code for those bottlenecks.

There are generally two options: optimize the code or change the design method. We usually choose the latter, because not calling the following code will improve the performance of the program more than calling some optimized code. A well-designed program can improve performance by simplifying code.

The following will provide some methods and techniques that are often used to improve the performance of JAVA programs in their design and coding.

1. Object generation and resizing.

A common problem in JAVA programming is not taking advantage of the functions provided by the JAVA language itself, resulting in a large number of objects (or instances) being generated. Because the system not only spends time generating objects, it may also spend time later garbage collecting and disposing of those objects. Therefore, generating too many objects will have a significant impact on the performance of the program.

Example 1: About String,StringBuffer, +, and Append

The JAVA language provides operations on String variables. However, if used improperly, the performance of the program will be affected.

The following statement:

  1. It may seem very lean, but it’s not. To generate binary code, perform the following steps and operations:

As you can see, these two simple lines of code generate five object variables STR1,STR2,STR3,STR4 and STRBUF1. Instances of these generated classes are typically stored in the heap.

The heap initializes the superclasses of all classes, the instances of the classes, and calls the architects of the classes and each of their superclasses. These operations are very resource-intensive. Therefore, it is necessary to restrict the generation of objects.

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

The system performs the following operations:

As you can see, the improved code generates only four object variables: STR1,STR2,STR3, and STRBUF_1. You might not think that generating one less object would make a big difference to the performance of your program.

But section 2 below will execute twice as fast as section 1. Because snippet 1 generates eight objects, snippet 2 only generates four.

Code snippet 1:

Snippet 2:

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. Its attention mainly has the following aspects;

1. Use Static Class Variables whenever possible.

If a variable in a class does not vary with its instances, it can be defined as a static variable that is shared by all of its instances.

Ex. :

Can be defined as:

2. Don’t make too many changes to the generated objects.

For some classes, such as the String class, it is preferable to regenerate a new object instance rather than modify an already generated object instance.

Ex. :

The code above generates three instances of objects of type String. The first two immediately need to be recycled by the system. If you concatenate strings, performance will be worse because the system will not have to generate more temporary variables for this purpose, as shown in Example 1 above.

When generating an object, allocate it a reasonable amount of space and size. Many classes in JAVA have their own default space allocation.

For the StringBuffer class, the default allocation size is 16 characters. If a StringBuffer is not 16 characters long enough to be used in a program, it must be properly initialized.

4. Avoid generating objects or variables that are rarely used or have a short lifetime.

In this case, you should define an object buffer pool. The overhead of managing an object buffer pool is much lower than the overhead of frequently generating and reclaiming objects.

5. Initialize only within the scope of the object.

JAVA allows you to define and initialize objects anywhere in your code. In this way, you can initialize only in the scope of the object. Thus saving system overhead.

Ex. :

You can change it to:

2. Abnormal (Exceptions)

The JAVA language provides try/catch to facilitate users to catch exceptions and handle exceptions. However, if used improperly, the performance of JAVA programs will be affected.

Therefore, the following two points should be noted:

1. Avoid trying/catching your application’s logic

If you can use logical statements like if,while, etc., then try/catch statements should be avoided as much as possible.

2. Reuse exceptions

When exception handling is necessary, reuse existing exception objects as much as possible. Generating an exception object consumes most of the time in exception handling.

  1. Thread (when)

Threads are commonly used in a high-performance application. Because threads make full use of system resources. The program can continue processing and running while other threads wait for data to be read or written from the hard disk or network. However, improper use of threads will also affect the performance of the program.

Example 2: Use Vector correctly

Vector is mainly used to hold objects of various types (both the same and different types). However, in some cases it can have a performance impact on the application. This is largely due to two features of the Vector class.

First, Vector provides thread safety. Even though many methods in the Vector class are synchronized. However, if you have confirmed that your application is single-threaded, synchronization of these methods is completely unnecessary.

Second, when a Vector looks for stored objects, it often takes a lot of time to match the types. When the objects are all of the same type, these matches are completely unnecessary.

Instead of the Vector class, it is necessary to design a single-threaded class or collection that holds objects of a specific type. The substitution program is as follows (stringvector.java) :

Therefore, the code:

It can be replaced with the following code:

This allows you to improve the performance of your JAVA programs by optimizing threads.

The following program is used for testing (testCollection.java) :

Note the following aspects about thread operations: 1. Avoid excessive synchronization

As shown above, unnecessary synchronization often degrades program performance. Therefore, if the program is single-threaded, synchronization must not be used.

2. Synchronize methods instead of entire code segments

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

3. Use multiple locks per object to increase concurrency.

There is usually only one “lock” per object, which means that a “deadlock” can occur if two threads execute two different synchronization methods on an object. Even though the two methods don’t share any resources. To avoid this problem, you can implement a “multi-lock” mechanism on an object.

As follows:

4. Input and Output (I/O)

Input and output are many things, but the most important are reading and writing to a hard disk, network, or database. For read and write operations, there are caches and no caches. For database operations, there are several types of JDBC drivers to choose from. Either way, it will affect the performance of the application.

Therefore, the following points need to be noted:

1. Use input/output buffers

Use caching as much as possible. However, it is recommended not to use caches if they are to be flushed frequently.

Output streams and Unicode strings

The Write class is expensive when using Output streams and Unicode strings. Because it implements Unicode to byte conversion. Therefore, if possible, implement the conversion before using the Write class or use the OutputStream class instead of the Writer class.

3. Use TRANSIENT when serializing

When serializing a class or object, use transient types for atomic types or elements that can be reconstructed. So you don’t have to serialize every time. This small change can make a big difference in performance if these serialized objects are to be transferred over the network.

4. Use Cache

For frequently used objects or data that doesn’t change much, you can store it in a cache. This can speed up access. This is especially important for result sets returned from the database.

5. Use fast JDBC drivers

JAVA provides four ways to access a database. Two of these are JDBC drivers. One is a local drive outsourced in 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.

  1. Some other experiences and tips

Xiaobian recently collected the Java programmer advanced architect information to do some collation, free to share with every learning Java friends. Need can enter the group: 751827870

-- -- -- -- -- - end -- -- -- -- -- - > the article by the blog article, multiple platform released [OpenWrite] (https://openwrite.cn?from=article_bottom).Copy the code