In Java programming, "for performance" should be done as much as possible (1)

Source: Internet
Author: User

Recently, the machine memory is full again. In addition to the new machine memory, we should also review our code. Many code compilation methods are too casual, these bad habits or lack of understanding of the programming language should be well suppressed.

The following is a summary of some of the network resources that should be done as much as possible in Java programming.

1. Use the singleton whenever possible

The use of Singleton can reduce the load burden, shorten the loading time, and improve the loading efficiency, but not all of them are applicable to singleton. Simply put, the Singleton is applicable to the following three scenarios:

First, control resource usage and control concurrent resource access through thread synchronization;

Second, control the generation of instances to save resources;

Third, control data sharing and allow communication between multiple irrelevant processes or threads without establishing a direct association.

2. Avoid using static variables whenever possible

You know, when an object is defined as referenced by the stataic variable, gc usually does not recycle the memory occupied by this object, such

 
 
  1. public class A{    
  2.  
  3. static B b = new B();    
  4.  
  5. }    

At this time, the lifecycle of static variable B is synchronized with class A. If Class A is not uninstalled, the object B is resident in the memory until the program ends.

3. Avoid creating too many Java objects.

Try to avoid new objects in the frequently called methods and loops. Because the system not only takes time to create objects, but also takes time to recycle and process these objects, within the scope that we can control, we recommend that you replace objects with basic data types or arrays to maximize the reuse of objects.

4. 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) All final methods, which are related to the specific compiler implementation ). This can increase the performance by an average of 50%.

5. Use local variables whenever possible

Parameters passed during method call and 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.

6. Try to handle the places of use of the packaging type and basic type

Although the packaging types and basic types can be converted to each other during use, the memory areas generated by the two are completely different. The basic types of data are generated and processed in the stack, the packaging type is an object that generates instances in the heap.

The packaging type is applicable to the processing of collection objects and objects. Other Processing Methods advocate the use of basic types.

7. Use synchronized with caution to minimize synchronize.

We all know that implementing synchronization requires a lot of system overhead as a cost, and may even cause deadlocks, so we should avoid unnecessary synchronization control as much as possible. When the synchronize method is called, the current object is directly locked. Other threads cannot call other methods of the current object until the method is executed. Therefore, the synchronize method should be as small as possible, and the method synchronization should be used instead of the code block synchronization.

8. Use StringBuilder and StringBuffer for string connection whenever possible

I will not talk about this much.

9. Try not to use the finalize method

In fact, it is very difficult to put the resource cleanup in the finalize method. Due to the heavy GC workload, especially when the Young generation memory is reclaimed, the application will be suspended, therefore, the finalize method can be used to clean up resources, resulting in a greater GC burden and worse program running efficiency.

10. Try to replace the object with the basic data type

 
 
  1. String str = "hello"; 

In this method, a "hello" string is created, and the JVM character cache pool also caches this string;

String str = new String ("hello ");

In this case, in addition to creating strings, the String object referenced by str also contains an array of char [] at the bottom layer. The array of char [] Stores h, e, l, l, o in sequence.

11. Use HashMap and ArrayList as much as possible for a single thread

HashTable and Vector use synchronization mechanisms to reduce performance.

12. Create a HashMap as reasonably as possible

When you want to create a large hashMap, make full use of another constructor.

Public HashMap (int initialCapacity, float loadFactor)

To prevent HashMap from performing hash reconstruction multiple times, resizing is a performance-consuming task. By default, initialCapacity is only 16, while loadFactor is 0.75, which indicates the capacity required, you 'd better accurately estimate the optimal size you need. The same is true for Hashtable and Vectors.

13. reduce repeated variable calculation as much as possible

For example

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

Should be changed

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

In addition, you should avoid using complex expressions in a loop. in a loop, loop conditions are calculated repeatedly. If you do not use a complex expression and keep the value of the loop condition unchanged, the program will run faster.

14. Avoid unnecessary creation as much as possible

For example

 
 
  1. A a = new A(); 
  2. if(i==1){list.add(a);} 

Should be changed

 
 
  1. f(i==1){ 
  2. A a = new A(); 
  3. list.add(a);} 

5. release resources in finally blocks as much as possible

The resources used in the program should be released to avoid resource leakage. This should be done in finally blocks. Regardless of the execution result of the program, the finally block is always executed to ensure that the resource is properly closed.

16. Use shift as much as possible to replace the operation of 'a/B'

"/" Is a very costly operation. Using shift operations will be faster and more effective.

For example

int num = a / 4; 

int num = a / 8; 

Should be changed

nt num = a >> 2; 

int num = a >> 3; 

Note that annotations should be added when shift is used, because the shift operation is not intuitive and difficult to understand.


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.