Java Performance Optimization Techniques summary _java

Source: Internet
Author: User
Tags error handling modifier sqlite database stringbuffer

The examples in this article Summarize Java performance optimization techniques. Share to everyone for your reference. The specific analysis is as follows:

Here is a reference to some books, network resources sorted out, suitable for most Java applications

In Java programs, most of the reason for performance problems is not in the Java language, but in the program itself. It is important to develop good coding habits that can significantly improve program performance.

1. Use the final modifier as much as possible.

A class with the final modifier is not derived. In the Java Core API, there are many examples of final application, 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 the opportunity to inline (inline) all final methods (this is related to the specific compiler implementation). This will increase performance by an average of 50%.

2. Reuse objects as much as possible.

In particular, in the use of String objects, you should use StringBuffer instead when strings are connected, 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 will have a significant impact on the performance of your program.

3. Use local variables as much as possible.

The parameters passed when the method is invoked and the temporary variables created in the call are saved in the stack (stack) faster. Other variables, such as static variables, instance variables, and so on, are created in the heap (Heap) in a slower speed.

4. Do not repeat initialization of variables.

By default, when the constructor of a class is invoked, Java initializes the variable to the determined value, all objects are set to NULL, the integer variable is set to 0,float and the double variable is set to 0.0, and the logical value is set to False. This should be especially noted when a class derives from another class, because when an object is created with the new keyword, all constructors in the chain of the constructor are invoked automatically.
Here's a note that when you set the initial value for a member variable but need to invoke another method, it's best to put it in a method such as initxxx (), because calling a method assignment directly may throw a null pointer exception because the class has not yet been initialized, public int state = This.getstate ( );

5. In the development of java+oracle application system, SQL language embedded in Java should use uppercase form as much as possible to reduce the parsing burden of Oracle parser.

6.java Programming process, the database connection, I/O flow operation, after the use, timely shutdown to release resources. because the operation of these large objects can result in a large overhead of the system.

7. Excessive creation of objects consumes a large amount of memory in the system, which can lead to memory leaks, so it is of great significance to ensure the timely recovery of expired objects.
The JVM's GC is not very intelligent, so it is recommended that you manually set the object to null after it has been used.

8. When using the synchronization mechanism, you should try to use method synchronization instead of code block synchronization.

9. To minimize the duplication of the calculation of variables.

Like what

 
 

should be amended to read

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

10. Adopt a policy that starts when you need it.

For example:

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

should be modified to:

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

11. Use exceptions with caution, and exceptions are bad for performance.

Throwing an exception begins by creating a new object. The constructor of the Throwable interface calls a local method named Fillinstacktrace (), and the Fillinstacktrace () method checks the stack to collect call tracking information. Whenever an exception is thrown, the VM must adjust the call stack because a new object is created during the process.

Exceptions can only be used for error handling and should not be used to control the process.

12. Do not use the Try/catch statement in the loop, the Try/catch should be placed at the outermost layer of the loop.

An error is a class that gets a system error, or a class that is a virtual machine error. Not all error exception can obtain, the virtual machine error exception cannot get, must obtain with the error.

13. By StringBuffer's constructor to set his initialization capacity, it can significantly improve performance.

The default capacity of StringBuffer is 16, and when StringBuffer capacity reaches its maximum capacity, she will increase its capacity to the current twice times +2, which is 2*n+2. Whenever StringBuffer reaches her maximum capacity, she has to create a new array of objects and then copy the old object array, which wastes a lot of time. So it is necessary to set a reasonable initialization capacity value for StringBuffer!

14. Reasonable use of java.util.Vector.

Vectors are similar to StringBuffer, and all existing elements are assigned to the new storage space each time the capacity is expanded. The vector's default storage capacity is 10 elements, and the expansion doubles.

Vector.add (Index,obj) This method inserts element obj into the index position, but both index and subsequent elements move one position downward (index plus 1). It is bad for performance unless necessary.

The same rule applies to the Remove (int index) method, removing the element at the specified position in the vector. Moves all subsequent elements to the left (the index is reduced by 1). Returns the element removed from this vector. So removing the last element of the vector is much less expensive than deleting the 1th element. It is best to remove all elements using the Removeallelements () method.

If you want to remove an element from a vector, you can use Vector.remove (obj) instead of retrieving the element position yourself, and then deleting it, such as int index = INDEXOF (obj); vector.remove (index);

15. Use System.arraycopy () when replicating large amounts of data;

16. Code refactoring to increase the readability of your code.

17. Create an instance of an object without the new keyword.

When you create an instance of a class with the new keyword, all constructors in the chain of the constructor are invoked automatically. 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 to
  new Credit ();
}
The improved code uses the Clone () method,
private static Credit Basecredit = new Credit ();
public static credit Getnewcredit ()
{return (credit)
  Basecredit.clone ();
}

18. Multiplication and division If you can use displacement, should try to use displacement, but it is best to add comments, because the displacement operation is not intuitive, difficult to understand.

19. Do not declare the array as: public static final.

20.HASPMAP traversal.

map<string, string[]> paramap = new hashmap<string, string[]> ();
For (entry<string, string[]> entry:paraMap.entrySet ())
{
  String Appfielddefid = Entry.getkey ();
  String[] values = Entry.getvalue ();
}

The result is obtained by using the hash value to get the corresponding entry, and the key and value are obtained directly after obtaining the entry value.

21.array (array) and the use of ArrayList.

Array arrays are the most efficient, but the capacity is fixed, unable to dynamically change, ArrayList capacity can grow dynamically, but at the expense of efficiency.

22. single-threaded should use HashMap as much as possible, ArrayList, unless necessary, otherwise do not recommend the use of Hashtable,vector, they use the synchronization mechanism, and reduce performance.

the difference between 23.stringbuffer,stringbuilder is that the Java.lang.StringBuffer is a thread-safe variable character sequence. A string buffer similar to strings, but cannot be modified. StringBuilder typically use the StringBuilder class as a priority when compared to this class, because she supports all the same operations, but is faster because she does not perform synchronization. In order to achieve better performance, you should try to specify her capacity when constructing StringBuffer or StringBuilder. Of course, if it's not more than 16 characters, it's not necessary.
In the same situation, using StringBuilder can only achieve a 10%~15% performance boost than using StringBuffer, but it risks multiple thread insecurity. Consider or recommend the use of StringBuffer.

24. Use basic data types as much as possible instead of objects.

25. Use simple numerical calculation instead of complex function calculation , such as look-up table method to solve the trigonometric functions problem.

26. Using specific analogies to use the interface is efficient, but the structural elasticity is reduced, but the modern IDE can solve this problem.

27. Consider using static methods

If you do not need to access the object outside, then make your method a static method. She will be called faster because she does not need a virtual function to guide the table. This colleague is also a good practice because she tells you how to differentiate the nature of the method, and calling this method does not change the state of the object.

28. The use of internal get,set methods should be avoided as far as possible.

In Android programming, calls to virtual methods have many costs, more than the cost of instance property queries. We should use the Get,set method when we outsource the call, but we should call it directly when we call it internally.

29. Avoid enumeration, use of floating-point numbers.

30. A two-D array takes up more memory space than a one-dimensional array, which is about 10 times times the computation.

31.SQLite database Read all the data of the whole table quickly, but conditional query is time-consuming 30-50ms, we do this aspect of the time to pay attention to, as little as possible, especially nesting search!

I hope this article will help you with your Java programming.

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.