Improve java program performance

Source: Internet
Author: User
Improve java program performance-general Linux technology-Linux programming and kernel information. The following is a detailed description. 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 this string
(9) Call the Constructor );
(10) Save the string to buffer it into 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 buffer it into 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 for STR_BUF_1. (STR_3)
(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 logic 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 . 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}
}
/*************** StringVector. java *****************/
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;
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; I ++)
{
Store. addElement ("string ");
}
Long finish = System. currentTimeMillis ();
System. out. println (finish-start ));
Start = System. currentTimeMillis ();
For (int I = 0; I <1000000; I ++)
{
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; I ++) {store. add ("string ");}
Long finish = System. currentTimeMillis ();
System. out. println (finish-start ));
Start = System. currentTimeMillis ();
For (int I = 0; I <1000000; I ++ ){
String result = store. getStringAt (I );
}
Finish = System. currentTimeMillis ();
System. out. println (finish-start ));
}
}
}
/**************** TestCollection. java *****************/
The test results are as follows (assuming the standard time is 1, the smaller the performance is, the better ):


Pay attention to the following aspects for thread operations.
(1) prevent excessive Synchronization
As shown above, unnecessary synchronization often causes program performance degradation. Therefore, if the program is a single thread, do not use synchronization.
(2) synchronous method instead of synchronizing the entire code segment
It is better to synchronize a method or function than to synchronize the entire code segment.
(3) Use multiple "locks" mechanism for each object to increase concurrency.
Generally, each object has only one "Lock", which indicates that if two threads execute two different Synchronization Methods of an object, a "deadlock" will occur ". Even if the two methods do not share any resources. To avoid this problem, you can implement a "Multi-lock" mechanism for 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 ++;
}
}
}
4. Input and Output (I/O)
Input and Output include many aspects, but the most involved is read and write operations on hard disks, networks, or databases. For read/write operations, there are cache and no cache; for database operations, there can be multiple types of JDBC drives to choose from. But in any case, it will affect the performance of the program. Therefore, pay attention to the following points:
(1) Use the input/output buffer
Use as much cache as possible. If you need to refresh the cache frequently (flush), we recommend that you do not use the cache.
(2) Output Stream and Unicode string
When Output Stream and Unicode strings are used at that time, the overhead of the Write class is relatively large. It must convert Unicode to byte. Therefore, if possible, it can be converted before using the Write class or replaced by the Writer class using the OutputStream class.
(3) Use transient when serialization is required
When serializing a class or object, the atomic type (atomic) or the element that can be reconstructed must be recognized as the transient type. This eliminates the need to serialize each time. If these serialized objects are to be transmitted over the network, this small change will greatly improve the performance.
(4) using high-speed Cache)
Objects or data that are frequently used but not changed can be stored in the cache. In this way, the access speed can be improved. This is especially important for the result set returned from the database.
(5) Use a fast JDBC Driver)
JAVA provides four methods for accessing the database. Two of them are JDBC drives. One is a local drive outsourced using JAVA; the other is a full JAVA drive. Which one should be used depends on the JAVA deployment environment and the application itself.
Related Article

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.