Java Performance Optimization Tips

Source: Internet
Author: User
Tags sqlite database

[Size=small] In Java programs, the most reason for performance problems is not the Java language, but 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 a final modifier is not derived. 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 consumer 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 Inline (inline) for all final methods (this is related to the specific compiler implementation). This will increase the performance by an average of 50%.

2. Reuse objects as much as possible.

In particular, in the use of string objects, strings should be used instead of stringbuffer, since the system not only takes time to generate objects, it may take time for them to be garbage collected and processed later. Therefore, generating too many objects will have a significant impact on the performance of the program.

3. Use local variables as much as possible.

The parameters passed when the method is called and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables, instance variables, and so on, are created in the heap and are slower.


4. Do not repeat the initialization of variables.

By default, when the constructor of a class is called, Java initializes the variable to a certain 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 is especially important when a class is derived from another class, because all constructors in the constructor chain are called automatically when an object is created with the new keyword.
Here's a note that when you set an initial value for a member variable but need to call another method, it's best to put it in a method such as initxxx (), because calling a method assignment might throw a null pointer exception because the class has not yet been initialized, public int state = This.getstate ( );


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


6.java programming process, the database connection, I/O flow operation, after the use is complete, close in time to release resources. Because the operation of these large objects can cause a large overhead on the system.

7. Excessive creation of objects consumes a large amount of memory in the system, which can cause memory leaks when critical, so it is important to ensure the timely recovery of outdated objects. The JVM's GC is not very intelligent, so it is recommended to manually set it to null after the object is used.

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

9. Minimize the repetition of variables.

Like what:

 for (int

should be amended to read

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

10. Adopt A strategy that starts when needed.
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 with creating a new object. The constructor of the Throwable interface calls the local method named Fillinstacktrace (), the Fillinstacktrace () method examines 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 the process.
Exceptions can only be used for error handling and should not be used for control procedures.


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

Error is a class that gets a system error, or a virtual machine error. Not all errors exception can be obtained, the virtual machine error exception can not be obtained, must be obtained by error.


13. By setting his initialization capacity through the StringBuffer constructor, performance can be significantly improved.

The default capacity of StringBuffer is 16, and when StringBuffer capacity reaches its maximum capacity, she increases her capacity to twice times the current +2, or 2*n+2. Whenever StringBuffer reaches her maximum capacity, she has to create a new array of objects and then copy the old array of objects, which can be a waste of time. Therefore, 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 each time the capacity is expanded, all existing elements are assigned to the new storage space. Vector has a default storage capacity of 10 elements, doubling the expansion.
Vector.add (Index,obj) This method inserts the element obj into the index position, but the index and subsequent elements move down one position in turn (adding 1 to its index). Performance is detrimental unless necessary.
The same rule applies to the Remove (int index) method, removing the element at the specified position in this vector. Shifts all subsequent elements to the left (index minus 1). Returns the element that is removed from this vector. So removing the last element of the vector is much less expensive than removing the 1th element. It is best to remove all elements with the removeallelements () method.
If you want to delete an element in a vector, you can use Vector.remove (obj), rather than retrieving the position of the element yourself, and then deleting it, such as int index = INDEXOF (obj); vector.remove (index);


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


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


17. 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 () {      returntonew credit (); }

The improved code uses the Clone () method,

Private Static New  Credit ();  publicstatic credits Getnewcredit () {   return  (credit)  Basecredit.clone (); }


18. Multiplication method If displacement can be used, the displacement should be used as far as possible, 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.

New Hashmap<string, string[]>();  for (entry<string, string[]> entry:paraMap.entrySet ()) {    = entry.getkey ();     = entry.getvalue ();}

Using the hash value to take out the corresponding entry to compare the results, obtain the value of entry directly after the key and value.

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

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


22. Single thread should try to use HashMap, ArrayList, unless necessary, it is not recommended to use Hashtable,vector, they use the synchronization mechanism, and reduce performance.

The difference between 23.stringbuffer,stringbuilder

Is:

Java.lang.StringBuffer A variable sequence of characters for thread safety. A string-like buffer, but cannot be modified. StringBuilder generally should prefer the StringBuilder class when compared to this class, because she supports all the same operations, but is faster because she does not perform synchronization. For better performance, you should try to specify her capacity when constructing StringBuffer or StringBuilder. Of course, no more than 16 characters.
In the same situation, using StringBuilder can only get 10%~15% performance gains compared to using stringbuffer, but it risks a multi-thread insecurity. It is recommended that stringbuffer be used in a comprehensive consideration.



24. Try to use the base data type instead of the object.

25. Use simple numerical calculations instead of complex function calculations, such as table-checking to solve trigonometric problems.

26. Using a specific analogy to use the interface is highly efficient, but the structural elasticity is reduced, but modern ides can solve this problem.

27. Consider using static methods, if you do not need to access the external object, then make your method static method. She will be called faster because she does not need a virtual function-oriented table. This colleague is also a good practice because she tells you how to distinguish the nature of the method, and calling this method does not change the state of the object.

28. The use of intrinsic get,set methods should be avoided wherever possible.

In Android programming, the invocation of a virtual method has a lot of cost, more than the cost of an instance property query. We should use the Get,set method when we outsource the call, but it should be called directly when it is called internally.

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

30. A two-D array consumes more memory space than a one-dimensional array, which is roughly 10 times times computed.

31.SQLite database reads all the data of the whole table quickly, but the conditional query will be time-consuming 30-50ms, we should pay attention to this aspect, as far as possible, especially nested search! [/size] [Align=left] [/align]

Java Performance Optimization Tips

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.