Summary of Java performance optimization tips

  • 2020-04-01 03:48:47
  • OfStack

This example summarizes Java performance optimization tips. Share with you for your reference. Specific analysis is as follows:

Here are some books, web resources sorted out, suitable for most Java applications

In JAVA programs, most of the performance problems are not in the JAVA language, but in the program itself. Developing good coding habits is important and can significantly improve program performance.

1. Use final modifiers whenever possible.

Classes with final modifiers are not derivable. In the JAVA core API, there are many examples of final applications, such as java.lang.string. Specifying final for the String class prevents the user from overwriting the length() method. In addition, if a class is final, all methods of that class are final. The Java compiler looks for opportunities to inline all final methods (depending on the specific compiler implementation). This can improve performance by an average of 50%.

Try to reuse objects.

In particular, in the use of String objects, stringbuffers should be used instead when String concatenation occurs, because the system not only takes time to generate objects, it may also take time to garbage collect and process those objects later. So generating too many objects can have a big impact on your program's performance.

3. Use local variables whenever possible.

The parameters passed when the method is called and the temporary variables created in the call are stored in the Stack, which is faster. Other variables, such as static variables, instance variables, etc., are created in the Heap and are slower.

4. Do not initialize variables repeatedly.

By default, when the constructor of the class is called, Java initializes the variable to a specified value, all objects are set to null, integer variables are set to 0, float and double variables are set to 0.0, and the logical value is set to false. This is especially important when a class is derived from another class, because when an object is created with the new keyword, all constructors in the constructor chain are automatically called.
One thing to note here is that when you set the initial value of a member variable but need to call other methods, it is better to put it in a method such as initXXX(), because calling a method assignment directly may throw a pointer exception because the class is not initialized. Public int state = this.getstate ();

5. In the application system development of Java +Oracle, the embedded SQL language in Java should be capitalized as much as possible to reduce the parsing burden of the Oracle parser.

6. In the process of Java programming, make database connection and I/O flow operation, and close it in time to release resources after use. Because the operation of these large objects will cause large system overhead.

7. Excessive object creation will consume a large amount of memory in the system, which will lead to memory leak in severe cases. Therefore, It is important to ensure timely recovery of expired objects.
The GC of the JVM is not very smart, so it is recommended that you manually set the object to null after it is used up.

8. When using a synchronization mechanism, try to use method synchronization instead of code block synchronization.

9. Minimize double counting of variables.

Such as


for(int i=0;i<list.size();i++) 

Should be modified to


for(int i=0,len=list.size();i<len;i++)

10. Adopt a policy that starts when needed.

Such as:


String str="abc";
if(i==1){ list.add(str);}

It should be amended to:


if(i==1){String str="abc"; list.add(str);}

11. Use exceptions with caution. Exceptions are bad for performance.

To throw an exception, you first create a new object. The constructor of the Throwable interface calls a local method named fillInStackTrace(), and the fillInStackTrace() method checks the stack and collects the call trace information. Whenever an exception is thrown, the VM must adjust the call stack because a new object is created during processing.

Exceptions can only be used for error handling and should not be used to control program flow.

12. Do not use a Try/Catch statement in a loop. Put a Try/Catch in the outermost layer of the loop.

Error is a class that retrieves system errors, or virtual machine errors. Not all Error exceptions can be obtained, the virtual machine Error Exception will not be obtained, you must use Error to obtain.

13. Using the constructor of StringBuffer to set its initialization capacity can significantly improve performance.

The default capacity of StringBuffer is 16, and when StringBuffer reaches its maximum capacity, it increases its capacity to 2 times +2, which is 2*n+2. Whenever StringBuffer reaches its maximum capacity, it has to create a new array of objects and then copy the old array of objects, which wastes a lot of time. Therefore, it is necessary to set a reasonable initialization capacity value for StringBuffer.

14. Use java.util.Vector wisely.

A Vector is similar to a StringBuffer in that every time the capacity is expanded, all existing elements are assigned to the new storage space. The default storage capacity of Vector is 10 elements, double the capacity.

Vector.add (index,obj) this method inserts the element obj into the index position, but the index and the subsequent elements in turn move down one place (adding 1 to their index). Unless necessary, this is bad for performance.

The same rule applies to the remove(int index) method, which removes the element at the specified position in the vector. Move all subsequent elements to the left (subtract 1 from their index). Returns the element removed from this vector. So deleting the last element of a vector is much less expensive than deleting the first element. Removing all elements is best done with the removeAllElements() method.

If you want to delete an element in a vector, you can use vector. Remove (obj); Instead of having to retrieve the element position and delete it, int index = indexOf (obj); The vector. Remove (index);

15. When copying large amounts of data, use system.arraycopy ();

16. Code refactoring to increase the readability of code.

Create an instance of the object without the new keyword.

When you create an instance of a class with the new keyword, all constructors in the constructor chain are automatically called. But if an object implements the Cloneable interface, we can call her clone() method. The clone() method does not call any class constructors.

The following is a typical implementation of the Factory pattern.


public static Credit getNewCredit()
{
  return new Credit();
}
 Improved code usage clone() Method, 
private static Credit BaseCredit = new Credit();
public static Credit getNewCredit()
{
  return (Credit)BaseCredit.clone();
}

18. If displacement can be used in multiplication and division, it should be used as much as possible, but it is better to add comments, because the displacement operation is not intuitive and difficult to understand.

19. Never declare an array as: public static final.

20. Traversal of aspmap.


Map<String, String[]> paraMap = new HashMap<String, String[]>();
for( Entry<String, String[]> entry : paraMap.entrySet() )
{
  String appFieldDefId = entry.getKey();
  String[] values = entry.getValue();
}

The hash value is used to fetch the corresponding Entry for comparison to get the result. After obtaining the value of the Entry, the key and value are directly taken.

21. Use of array and ArrayList.

Array arrays are the most efficient, but their capacity is fixed and cannot be changed dynamically. ArrayList capacity can be dynamically increased at the expense of efficiency.

22. Single thread should use HashMap and ArrayList whenever possible. HashTable and Vector are not recommended unless necessary.

23. The StringBuffer, the difference between the StringBuilder In: java.lang.stringbuffer thread-safe variable character sequences. A String buffer that is similar to a String, but cannot be modified. StringBuilder should generally be preferred over this class because it supports all the same operations, but because it does not perform synchronization, it is faster. For better performance, try to specify her capacity when constructing a StringBuffer or StringBuilder. Of course not if you don't have more than 16 characters.
In the same case, using StringBuilder provides only a 10 to 15 percent performance improvement over using StringBuffer, but risks the insecurity of multithreading. All things considered, StringBuffer is recommended.

Replace objects with basic data types whenever possible.

Replace complex functional calculations with simple numerical ones , such as looking up the table to solve trig function problems.

26. Using concrete analogies to use interfaces is efficient, but the structure is less elastic, but modern ides can solve this problem.

27. Consider using static methods

If you don't have to access the outside of the object, make your methods static. She will be called faster because she does not need a virtual function guide table. This colleague is also a good practice because she shows you how to distinguish between the properties of methods that call without changing the state of the object.

28. The inherent GET and SET methods should be avoided whenever possible.

In android programming, the invocation of virtual methods incurs more costs than instance property queries. We should only use get and set methods when outsourcing calls, but we should call them directly when making internal calls.

Avoid enumerations, floating point Numbers.

A 2-d array takes up more memory space than a 1-d array, about 10 times more than a 1-d array.

31.SQLite database can read all the data of the entire table very quickly, but the conditional query will take 30-50ms. Use them sparingly, especially nested lookups!

I hope this article has been helpful to your Java programming.


Related articles: