Java performance optimization skills

Source: Internet
Author: User

In Java programs, most of the reason for performance problems is not the Java language, but the program itself. Developing good coding habits is very important and can significantly improve program performance.

1. Try to use the final modifier.
Classes with final modifiers cannot be derived. There are many examples of final applications in the Java core API, 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 the class are final. The Java compiler will look for opportunities to inline (Inline) All final methods (this is related to the specific compiler implementation ). This can increase the performance by an average of 50%.

2. Try to reuse objects.
In particular, the use of string objects should be replaced by stringbuffer in case of string connection. Because the system not only takes time to generate objects, it may also take time to recycle and process these objects. Therefore, generating too many objects will greatly affect the program performance.

3. Use local variables whenever possible.
The parameters passed during method calling and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables and instance variables, are created in heap, which is slow.

4. Do not reinitialize the variable.
By default, Java initializes the variable to a definite value when calling the class constructor. All objects are set to null, and integer variables are set to 0, set float and double variables to 0.0 and logical values 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.
Note that when you set an initial value for a member variable but need to call other methods, you 'd better put it in a method such as initxxx, if you call a method to assign values directly, the NULL pointer may be thrown because the class has not been initialized. Public int state = This. getstate ();

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

6. During Java programming, database connections and I/O Stream operations are performed. after use, the database is closed in time to release resources. Because the operations on these large objects will cause a large overhead of the system.

7. Excessive object creation will consume a large amount of memory in the system. In severe cases, memory leakage will occur. Therefore, it is important to ensure timely recovery of expired objects.
Jvm gc is not very intelligent. Therefore, we recommend that you manually set it to null after the object is used.

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

9. reduce repeated calculation of variables as much as possible.
For example, for (INT I = 0; I <list. size (); I ++) should be modified to for (INT I = 0, Len = List. size (); I <Len; I ++)

10. Use the policy created only when necessary.
Example: String STR = "ABC ";
If (I = 1) {list. Add (STR );}
To:
If (I = 1) {string STR = "ABC"; List. Add (STR );}

11. Use exceptions with caution. Exceptions are detrimental to performance.
To throw an exception, you must first create a new object. The constructor of the throwable interface calls a local method named fillinstacktrace (). The fillinstacktrace () method checks the stack and collects Call trace information. As long as an exception is thrown, the VM must adjust the call stack because a new object is created during the processing.
Exceptions can only be used for error handling and should not be used to control program processes.

12. Do not use the try/catch statement in the loop. Place try/catch in the outermost layer of the loop.
An error is a class that gets system errors, or a virtual machine error. Not all error exceptions can be obtained. The exception cannot be obtained when the VM reports an error and must be obtained using an error.

13. The stringbuffer constructor is used to set the initialization capacity, which can significantly improve the performance.
The default capacity of stringbuffer is 16. When the capacity of stringbuffer reaches the maximum capacity, she will increase her capacity to 2 times + 2, that is, 2 * n + 2. At any time, as long as the stringbuffer reaches her maximum capacity, she had to create a new array of objects and then copy the old array of objects, which would waste a lot of time. Therefore, it is necessary to set a reasonable initial capacity value for stringbuffer!

14. Use Java. util. Vector properly.
Vector is similar to stringbuffer. When capacity is expanded, all existing elements must be assigned to the new bucket. The default storage capacity of vector is 10 elements, which doubles the capacity expansion.
Vector. Add (index, OBJ) This method can insert the element OBJ to the index position, but the index and subsequent elements must move down one position (add its index to 1 ). Performance is not good unless necessary.
The same rule applies to the remove (INT index) method to remove elements at the specified position in this vector. Remove all subsequent elements to the left (delete the index by 1 ). Returns the removed element from the vector. Therefore, deleting the last element of a vector is much less costly than deleting 1st elements. It is best to delete all elements using the removeallelements () method.
If you want to delete an element in a vector, you can use vector. remove (OBJ); you do not have to retrieve the element location by yourself, and then delete it, such as int Index = indexof (OBJ); vector. remove (INDEX );

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

16. Code refactoring increases the readability of the Code.

17. Create an instance of the object without the new keyword.
When you create an instance 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 constructor.
The following is a typical Implementation of the factory mode.
Public static credit getnewcredit ()
{
Return new credit ();
}
The improved code uses the clone () method,
Private Static credit basecredit = new credit ();
Public static credit getnewcredit ()
{
Return (credit) basecredit. Clone ();
}

18. If displacement can be used by multiplication and division, try to use displacement, but it is best to add a comment because the displacement operation is not intuitive and difficult to understand.

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

20. Traverse haspmap.
Map <string, string []> paramap = new hashmap <string, string []> ();
For (Entry <string, string []> entry: paramap. entryset ())
{
String appfielddefid = entry. getkey ();
String [] values = entry. getvalue ();
}
Use the hash value to retrieve the corresponding entry for comparison and obtain the value of the entry, and then directly obtain the key and value.

21. Use of array and arraylist.
Array array has the highest efficiency, but its capacity is fixed and cannot be changed dynamically. The arraylist capacity can be dynamically increased, but the efficiency is sacrificed.

22. hashmap and arraylist should be used as much as possible in a single thread. Unless necessary, hashtable and vector are not recommended. They use synchronization mechanisms to reduce performance.

23. The difference between stringbuffer and stringbuilder is that Java. Lang. stringbuffer thread-safe variable character sequences. A string buffer similar to a string, but cannot be modified. Compared with this class, stringbuilder should generally use the stringbuilder class first, because she supports all the same operations, but because she does not execute synchronization, It is faster. To achieve better performance, we should specify her capacity when constructing stringbuffer or stringbuilder. Of course, it will not be used if it cannot exceed 16 characters.
In the same case, stringbuilder can only obtain 10% ~ The performance is improved by 15%, but the risk of multi-thread security is required. We recommend that you use stringbuffer.

24. Try to use basic data types instead of objects.

25. Use simple numeric computing instead of complex function computing. For example, you can use a look-up table to solve the trigonometric function problem.

26. The usage of specific analogy interfaces is highly efficient, but the structure elasticity is reduced, but modern IDE can solve this problem.

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

28. Avoid using the internal get and set methods whenever possible.
In Android programming, calling of Virtual Methods incurs a lot of costs, which is more costly than querying instance properties. We should use the get and set methods only during outsourcing calls, but should call them directly during internal calls.

29. Avoid enumeration. Use floating point numbers.

30. The two-dimensional array occupies more memory space than the one-dimensional array, which is about 10 times the calculation.

31. the SQLite database quickly reads all the data in the entire table, but conditional queries take 30-50 ms. You should pay attention to this aspect and try to use it as little as possible, especially nested searches!

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.