How to optimize JAVA program development and improve JAVA Performance

Source: Internet
Author: User

You can use some auxiliary tools to locate the bottleneck in the program and then optimize the code of the bottleneck. There are generally two solutions: optimize the code or change the design method. We usually select the latter, because not calling the following code is better than calling some optimized code to improve the performance of the program. A well-designed program can streamline code and improve performance.

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

1. Object generation and size adjustment.

A common problem in JAVA programming is that the functions provided by the JAVA language are not used properly, so a large number of objects (or instances) are often generated ). Because the system not only takes time to generate objects, it may take time to recycle and process these objects. Therefore, generating too many objects will greatly affect the program performance.

Example 1: String, StringBuffer, +, and append

The JAVA language provides operations for String-type variables. However, improper use may affect the program performance. The following statement:

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

It seems to have been quite streamlined, but not actually. To generate binary code, perform the following steps and operations:

(1) generate a new String (STR_1 );
(2) copy the string;
(3) load the String constant "HuangWeiFeng" (STR_2 );
(4) Constructor );
(5) Save the string to the array (starting from position 0 );
(6) obtain the static out variable from the java. io. PrintStream class;
(7) generate a new string buffer variable new StringBuffer (STR_BUF_1 );
(8) copy the buffer variable of the string;
(9) Call the Constructor );
(10) Save the string to the array (starting from position 1 );
(11) using STR_1 as the parameter, call the append method in the string buffer class;
(12) load the String constant "is my name" (STR_3 );
(13) using STR_3 as the parameter, call the append method in the string buffer class;
(14) execute the toString command for STR_BUF_1;
(15) Call the println method in the out variable to output the result.

The two simple lines of code generate five object variables STR_1, STR_2, STR_3, STR_4, and STR_BUF_1. The instances of these generated classes are generally stored in the heap. The heap needs to initialize the super classes and class instances of all classes, and also call the framework of every super class of the class. These operations consume a lot of system resources. Therefore, it is necessary to limit 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 perform the following operations:

(1) generate a new string buffer variable new StringBuffer (STR_BUF_1 );
(2) copy the buffer variable of this string;
(3) load the String constant "HuangWeiFeng" (STR_1 );
(4) Call the Constructor );
(5) Save the string to the array (starting from position 1 );
(6) obtain the static out variable from the java. io. PrintStream class;
(7) Load STR_BUF_1;
(8) load the String constant "is my name" (STR_2 );
(9) using STR_2 as the parameter, call the append method in the string buffer instance;
(10) execute the toString command (STR_3) for STR_BUF_1 );
(11) Call the println method in the out variable to output the result.

It can be seen that the improved code only generates four object variables: STR_1, STR_2, STR_3 and STR_BUF_1. you may think that generating less than one object will not greatly improve the program performance. However, the execution speed of code segment 2 below will be twice that of code segment 1. Because code segment 1 generates eight objects, while code segment 2 generates only four objects.

Code Segment 1:

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

Code Segment 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 the JAVA program. The main points of attention are as follows;

(1) use Static Class Variables as much as possible)

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

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

It can be defined:
Public class foo
{
Static SomeObject so = new SomeObject ();
}

(2) do not change the generated object too much.

For some classes (such as the String class), we would rather regenerate a new object instance than modifying the generated object instance.
Example:
String name = "Huang ";
Name = "Wei ";
Name = "Feng ";

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

(3) When generating an object, allocate reasonable space and size to it. Many classes in JAVA have their default space allocation size. For the StringBuffer class, the default allocated space is 16 characters. If the size of the space used by StringBuffer in the program is not 16 characters, initialization must be performed correctly.

(4) avoid generating unused objects or variables with short lifecycles. In this case, an object buffer pool is defined. The overhead of managing an Object Buffer Pool is much lower than that of frequently generated and recycled objects.

(5) Only initialize within the scope of the object. JAVA allows objects to be defined and initialized anywhere in the code. In this way, initialization can only be performed within the scope of the object. This saves system overhead.

Example:
SomeObject so = new SomeObject ();
If (x = 1) then
{
Foo = so. getXX ();
}

It can be changed:
If (x = 1) then
{
SomeObject so = new SomeObject ();
Foo = so. getXX ();
}

2. Exceptions)

In JAVA, try/catch is provided to help you catch and handle exceptions. However, improper use may also affect the performance of JAVA programs. Therefore, pay attention to the following two points:

(1) Avoid using try/catch for application logic
If you can use logical statements such as if and while, try not to use try/catch statements.

(2) Reuse exception
When exceptions must be handled, try to reuse existing exceptions as much as possible. It takes most of the time to generate an exception object during exception handling.


3. Threading)

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

Example 2: Correctly Use the Vector class
Vector is mainly used to save various types of objects (including objects of the same type and different types ). However, in some cases, application performance may be affected. This is mainly determined by the two features of the Vector class. First, Vector provides thread security protection. Even if many methods in the Vector class are synchronized. However, if you have confirmed that your application is a single thread, the synchronization of these methods is completely unnecessary. Second, it usually takes a lot of time to perform type matching when Vector searches for various objects stored. However, when these objects are of the same type, these matches are completely unnecessary. Therefore, it is necessary to design a single-threaded program to save classes or collections of 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 previusly 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, the JAVA program performance can be improved by optimizing the thread. The program used for testing is as follows (TestCollection. java ):

Import java. util. Vector;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.