java reconstruction techniques commonly used

The basic principle

1. Try to use the right occasion singleton
singleton can reduce the burden of load, reduce the time to load and improve the efficiency of the load, but not all places are suitable for a single case, in simple terms, is intended for a single case three aspects:
first, the control of resources used by thread synchronization controlling concurrent access to resources;
second, control generates instance, in order to save resources;
third, shared control data, not directly related to the establishment of under conditions to allow multiple processes or threads communicate between unrelated.
2. Try to avoid using static random variable
You know, when an object is defined as static variables are referenced, usually GC does not reclaim the memory occupied by the object, such as

public class A{ 
   private static B b = new B(); 
}

At this static variable b life cycle synchronized with the Class A, Class A if not uninstall, then b objects of permanent memory, until the program is terminated.

3. Try to avoid too much too often to create Java objects
try to avoid the method is often called, loop new objects, due to the system not only takes time to create objects, but also to spend time on these objects for garbage collection and disposal, in we can control the range of the maximum object reuse, the best use an array of basic data types or objects instead.

4. Try to use the final modifier
with the final modifier class is not derived. In the core JAVA API, there are many examples of the final application, e.g. java.lang.String, prevents the user specified final covering length () method of class String. Further, if a class is final, then all such methods are final. java compiler will look for opportunities to inline (inline) all of the final method (which the compiler and the specific implementation dependent). This can improve the performance by an average of 50%.
Such as: let within the instance variable access getter / setter methods become "final:
simple getter / setter methods should be set to the final, which will tell the compiler that this method will not be overloaded, it can become" inlined ",example:

class MAF { 
     public void setSize (int size) { 
          _size = size; 
     } 
     private int _size; 
}
 
更正
 
class DAF_fixed { 
     final public void setSize (int size) { 
          _size = size; 
     } 
     private int _size; 
}

The possible use of local variables
pass method call parameters and temporary variables are created in the call stored in the stack (Stack), the faster. Other variables, such as static variables, instance variables, etc., are in the heap (Heap) to create, slowly.

6. Try to handle the package type and place of use of both basic types
, although the type of packaging and during use basic types can be interchangeable, but they both memory area is generated completely different basic types of data processing and generation are treated in the stack, a package type object in the heap is generated instance. In the collection class object has an object type of process suitable for packaging need, other processes advocate the use of basic types.

7. caution synchronized, methods to minimize synchronize
all know, is synchronized to a lot of overhead expense, and may even cause a deadlock, so try to avoid unnecessary synchronization control. When synchronize method is called, it will direct the current object lock, other threads can not call other methods of the current object before executing the method. Method synchronize it as small as possible, and should be used instead of the sync block synchronization method.

8. make use StringBuilder string concatenation and StringBuffer

9. Try not to use finalize methods
in fact, the resource cleanup completed on finalize method is a very bad choice, GC due to the large amount of work, especially when recycled Young generation of memory, the Metropolitan cause the application to be suspended, so and then choose to use finalize method to clean up resources, will lead to a greater burden on GC, process efficiency worse. In addition, the root cause is not recommended for use finalize method is that, JVM specification does not guarantee when to perform the method, so use this method to release the resources are not appropriate, may cause long resources were not released.
10 make use of the basic data types in place of object

String str = "hello";

Above this way will create a "hello" string, and JVM character string buffer pool will be cached;

String str = new String("hello");

At this time, in addition to the program to create a string, String str underlying objects referenced further comprises a char [] array, the char [] array are sequentially stored for h, e, l, l, o

11. The multi-threaded use map, list the principles
in a non-thread safe occurred premise should use HashMap, ArrayList, HashTable, Vector, etc. using the synchronous mechanism, reducing the performance.

12. Try to create a reasonable HashMap
when you want to create a relatively large hashMap, take advantage of this constructor

public HashMap(int initialCapacity, float loadFactor); 

Avoid HashMap conducted several hash reconstruction, expansion is a very performance-consuming thing, in default of initialCapacity only 16, but loadFactor 0.75, how much capacity, you'd better be able to accurately estimate what you need the best size, same Hashtable, Vectors is the same reason.

13. Repeat minimize calculated variables
, such as:

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

Should be changed

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

And in the loop should avoid the use of complex expressions, in a loop, the loop condition will be repeated computing faster, without the use of complex expressions, the value of the same cycling conditions, the program will run.

14. Try to avoid unnecessary creation
such as:

A a = new A();
 
if(i==1){list.add(a);}
应该改为
if(i==1){
  A a = new A();
  list.add(a);
}

15. The release of resources as far as possible in the finally block
the resources used in the program should be released, to avoid resource leaks. This is best done in a finally block. Regardless of the outcome of program execution, finally block will always be performed to ensure proper shutdown of resources.

16. Try to determine the capacity of the StringBuffer
StringBuffer constructor creates a default size (usually 16) of an array of characters. In use, if you exceed this size, it will re-allocate memory, creating a larger array and copy over the original array, then discard the old array. In most cases, you can specify when you create StringBuffer size, thus avoiding the automatic increase in capacity is not enough time to improve performance.
Such as:
the StringBuffer the StringBuffer new new Buffer = (1000);

17. Try to release as early as useless reference to the object
when the most part, the local method reference object variables referenced with the end of the method will become garbage, therefore, most of the time without having to program locally, reference variables explicitly set to null.
For example:
the Java Code

Public void test(){      
  Object obj = new Object();      
  …… 
 
  Obj=null;      
}

Above this there is no need, as the method of implementation of the completion test (), the program obj reference variable scoping is over. But if it is changed to the following:

   Public void test(){      
      Object obj = new Object();      
      ……      
      Obj=null;      
      //执行耗时,耗内存操作;或调用耗时,耗内存的方法     
      …… 
  }

This time it is necessary to assign obj is null, we can release the reference to the Object object as soon as possible.

18. Try to avoid using a two-dimensional array of
memory space occupied by the two-dimensional data much more than a one-dimensional array, probably more than 10 times.

19. Try to avoid using split
unless it is necessary, otherwise you should avoid using split, split due to the support for regular expressions, so the efficiency is relatively low, if dozens, hundreds of millions of frequent calls will cost a lot of resources, if you really need frequent calls split, consider using the apache StringUtils.split (string, char), you can cache the results of frequently split.

20. ArrayList & LinkedList
a linear table, a linked list, a word, make use of random queries ArrayList, ArrayList LinkedList superior, but also move the pointer LinkedList, remove the add operation LinkedList than ArrayList, ArrayList also move data, but this is the theoretical analysis, not necessarily the case, it is important to understand who in good 2 data structure, the right medicine.

21. Try to use System.arraycopy () instead of an array to loop reproduction by
System.arraycopy () to copy faster than the arrays through the circulation

22. Try to cache frequently used objects
objects as possible to cache frequently used, you can use an array, or HashMap cache of container, but this approach may cause the system to take up too much cache, performance degradation, you can use some recommended third-party open source tools such as EhCache, Oscache cache, they basically have achieved a FIFO / FLU such as caching algorithms.

23. Try to avoid very large memory allocation
Sometimes the problem is not caused by the then state of the heap, but because by allocation failure. Allocate blocks of memory must be contiguous, and as the heap fills up, finding large contiguous blocks more difficult.

24. Abnormal caution
when creating an exception, a need to collect trace stack (stack track), the exception stack is used to describe trace where created. Need to do a snapshot of the runtime stack when building these stack traces, it is a large part of this cost. When you need to create a Exception, JVM have to say: first, do not move, I want to keep a snapshot on your way now, so temporarily stop push and pop operations. Not only contains the runtime stack trace one or two elements of the stack, but encompasses every element of the stack.
If you create an Exception, you have to pay the price. Fortunately, the cost of capture is not an exception, so you can use try-catch will be the core wrap. Technically, you can even casually thrown, without spending a great price. Incur performance loss is not the throw operation - although it is thrown in the absence of pre-created unusual anomaly is a bit unusual. The true cost of takes is to create an exception. Fortunately, good programming practice has taught us, it should not be willy-nilly throw an exception. Abnormal is abnormal and design, but also should keep in mind when using this principle.

25. A reusable object as far as possible
especially in a String object, using the connection string should appear StringBuffer place, not only because the system takes time to generate the object, you may also need to spend time after these objects for garbage collection and disposal. Thus generating excessive object will have a big impact to the performance of the program.

26. Do not repeat initialize variables
default constructor call when the class, java will initialize variables to determine the values of all the objects is set to null, an integer variable to 0, float and double variable is set to 0.0, the logic value is set to false. When a class is derived from another class, this is especially should pay attention to, because when you create an object using the new keyword, all constructors are constructor in the chain is automatically invoked.
Here is a note to the member variable is set to an initial value but you need to call other methods, the best on a method such as initXXX (), as a direct call assignment method may be because the class has not been initialized pointer exception while short-selling, such as : public int state = this.getState () ;

27. Try to use uppercase database statements
in java Oracle's application development + in, java embedded SQL language should make full use of capitalization, in order to reduce the burden of parsing Oracle parser.

28. close the data connection
in the java programming, database connections, I / O stream operations, after use, to close the release of resources. Because the operation of these large objects can cause large overhead system.

29. The object is not used in a timely manner to set a null
creating objects too will consume a large amount of system memory, when severe, can lead to memory leaks, therefore, to ensure the timely recovery of expired objects of great significance. JVM's GC is not very intelligent, it is recommended after the object use, manually set to null.
Most of the time, the local method reference object variables referenced with the end of the method will become garbage, therefore, most of the time without having to program locally, reference variables explicitly set to null.
E.g:

Public void test(){ 
Object obj = new Object(); 
…… 
Obj=null; 
} 
上面这个就没必要了,随着方法test()的执行完成,程序中obj引用变量的作用域就结束了。但是如果是改成下面:
Public void test(){ 
Object obj = new Object(); 
…… 
Obj=null; 
//执行耗时,耗内存操作;或调用耗时,耗内存的方法 
…… 
}

30. Do not use Try / Catch statement in the loop, should the Try / Catch on the outermost loop

Error is to get the system wrong class, or a virtual machine the wrong class. Not all errors Exception can be acquired, the virtual machine will not obtain Exception error must be obtained by Error.

31. His initial capacity is set by the constructor StringBuffer, can significantly improve performance

StringBuffer default capacity is 16, when the capacity reaches the maximum capacity StringBuffer, she will increase their current capacity +2 twice, i.e. 2 * n + 2. Whenever StringBuffer reach her maximum capacity, she would have to create a new array object, then copy the old array of objects, which will waste a lot of time. So StringBuffer to set a reasonable initial capacity value, it is necessary

32. The rational use of java.util.Vector

Vector and StringBuffer similarly, each time expanding capacity, all existing elements to be assigned to the new storage space. Vector is the default storage capacity of 10 elements, expansion doubled.
vector.add (index, obj) This method may be inserted into the index position obj element, but the element index, and sequentially after a position to be moved downward (to their indices). Unless necessary detrimental to performance. The same rule applies to remove (int index) method, to remove this vector elements specified position. All subsequent elements to the left (which is the index minus 1). Returns the elements in this vector removed. So delete the last element of a vector than delete the first element of a much lower cost. Removes all elements with the best removeAllElements () method.
If you want to delete an element in the vector can be used vector.remove (obj); elements without having to retrieve their own position, then delete, such as

int index = indexOf(obj);vector.remove(index);

33. no new keyword to create an object instance is
an instance of the class is created with the new keyword, all constructors are constructor in the chain is called automatically. But if an object implements the Cloneable interface, we can call her clone () method. clone () method does not invoke any type constructor.
The following is a typical implementation mode Factory:

    public static Credit getNewCredit() 
    { 
        return new Credit(); 
    } 
    改进后的代码使用clone()方法:
    private static Credit BaseCredit = new Credit(); 
    public static Credit getNewCredit() 
    { 
        return (Credit)BaseCredit.clone(); 
    }

34. 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(); 
}

Direct access to the key and then using a hash value corresponding to the value taken Entry comparison result obtained, to obtain the values ​​of the entry.

35. array using (array) and ArrayList of
the highest array array efficiency, but the capacity is fixed and can not be changed dynamically, ArrayList can dynamically increase capacity, but at the expense of efficiency.

36. StringBuffer, StringBuilder difference between the
variable sequence of characters java.lang.StringBuffer thread-safe. String is similar to a string buffer, but can not be modified. Compared with the StringBuilder class, priority should generally use the StringBuilder class, because she supports all of the same operation, but because she did not perform synchronization, so faster. For better performance, the specified her capacity as possible should be configured StringBuffer or StringBuilder. Of course, if no more than 16 characters would not have had. Under the same circumstances, than using StringBuilder StringBuffer only get 10% to 15% performance increase, but bear the risk of multithreading unsafe. Considering it is recommended to use StringBuffer.

37. The basic data types used instead to make use of the object.

38. Consider using static methods
outside if you do not need to access the object, then make your way to become a static method. She will be faster to call, because she does not need a guided virtual function tables. This colleague is a good practice, because she tells you how to distinguish the nature of the process, calling this method does not change the state of the object.

39. Avoid using internal GET, SET method possible
40. Avoid using complex expressions in a loop condition
in the case of not optimizing compiler, in a loop, the loop condition will be repeated calculations, without the use of complex expressions , the value of the same cycling conditions, the program will run faster. example:

import java.util.Vector; 
    class CEL { 
         void method (Vector vector) { 
             for (int i = 0; i < vector.size (); i++)   // Violation 
                 ; // ... 
         } 
    } 
    
    更正:    
    
    class CEL_fixed { 
         void method (Vector vector) { 
             int size = vector.size () 
             for (int i = 0; i < size; i++) 
                 ; // ... 
         } 
    }

41. 'Vectors' and 'Hashtables' is defined as the initial size of the
JVM as Vector expanded size when the need to re-create a larger array, copy the contents of the original over the original array, and finally, the original array is then recycled. Visible to expand the capacity of Vector is a time-consuming thing.
Typically, the default size of 10 elements is not enough. You'd better be able to accurately estimate the optimal size you need. example:

import java.util.Vector; 
public class DIC { 
     public void addObjects (Object[] o) { 
         // if length > 10, Vector needs to expand 
         for (int i = 0; i< o.length;i++) {    
             v.add(o);    // capacity before it can add more elements. 
         } 
     } 
     public Vector v = new Vector();   // no initialCapacity. 
}

Correction:
set their own initial size.

public Vector v = new Vector(20);  
public Hashtable hash = new Hashtable(10);

42. Close Stream finally block
used in the program to resources should be released, to avoid resource leaks. This is best done in a finally block. Regardless of the outcome of program execution, finally block will always be performed to ensure proper shutdown of resources.
43. For a constant string, with 'String' instead of 'StringBuffer'
constant string does not need to dynamically change the length.
example:

public class USC { 
     String method () { 
         StringBuffer s = new StringBuffer ("Hello"); 
         String t = s + "World!"; 
         return t; 
     } 
}

Correction: The StringBuffer into String, String if it is determined this will not change, then it will reduce operating expenses to improve performance.
44. In addition, when a string using '' instead of "",
if the string is one character words
example:

public class STR { 
     public void method(String s) { 
         String string = s + "d"   // violation. 
         string = "abc" + "d"       // violation. 
     } 
}

Correction: The replacement string into a character '

public class STR { 
     public void method(String s) { 
         String string = s + 'd' 
         string = "abc" + 'd'   
     } 
}

Classes and methods optimization

No.1: Repeat the code to extract
duplicate code is one of the largest reconstruction little way, were the cause of reconstruction does not need to say more. It has many obvious benefits, such as greatly reduced total code, easy to maintain, more legible code is structured.
Its focus is to find duplicate code to complete the code among a particular sub-functions, please do not hesitate to find later move it to the appropriate method among them and stored in the appropriate class.
Small example

class BadExample {

    public void someMethod1(){
        //code
        System.out.println("重复代码");/* 重复代码块 */
        //code
    }
    
    public void someMethod2(){
        //code
        System.out.println("重复代码");/* 重复代码块 */
        //code
    }    
}

/* ---------------------分割线---------------------- */

class GoodExample {

    public void someMethod1(){
        //code
        someMethod3();
        //code
    }
    
    public void someMethod2(){
        //code
        someMethod3();
        //code
    }
    
    public void someMethod3(){
        System.out.println("重复代码");/* 重复代码块 */
    }    
}

No.2: long division method of
dividing the relevant lengthy process, in fact, sometimes abstract and code duplication is closely connected, often repeated in the course of our refining code, unknowingly completed one long division method. If after you extract most of the duplicate code, still retained some of lengthy method, then we must stop these lengthy special methods to deal with.
This one thing is worth noting, since when we split a big way most of them are against some of the functions which the division, so we need to give each child a function from the method name right, it is very important.
Small example

class BadExample {

    public void someMethod(){
        //function[1]
        //function[2]
        //function[3]
    }    
}

/* ---------------------分割线---------------------- */

class GoodExample {

    public void someMethod(){
        function1();
        function2();
        function3();
    }
    
    private void function1(){
        //function[1]
    }
    
    private void function2(){
        //function[2]
    }

    private void function3(){
        //function[3]
    }    
}

No.3: Nesting Optimization conditional branch (1)
a large number of nested conditional branch is very easy to code is prohibitive, we should try to avoid this code. Although structural principles have been saying that a function can have only one exit, but in such a large number of nested conditional branch, let us forget this so-called rule of it.
There is a term called health professional statement, you can treat this terrible nested conditional statements. Its core idea is that the situation does not meet certain conditions in front of the method, and promptly jump out method, so as not to affect the back of the judge. After the surgery, the code would look very sharp
small example

class BadExample {

    public void someMethod(Object A,Object B){
        if (A != null) {
            if (B != null) {
                //code[1]
            }else {
                //code[3]
            }
        }else {
            //code[2]
        }
    }    
}

/* ---------------------分割线---------------------- */

class GoodExample {

    public void someMethod(Object A,Object B){
        if (A == null) {
            //code[2]
            return;
        }
        if (B == null) {
            //code[3]
            return;
        }
        //code[1]
    }    
}

No.4: optimizing nested conditional branch (2)
where said nested conditional branching and slightly different from the above, it can not be used to optimize the health statement, but rather the terms of the merger branch, in order to achieve the code clear the goal of. It can also be seen from the two, nested conditional branch which should be avoided in the coding, it would greatly reduce the readability of the code.
Small example

class BadExample {

    public void someMethod(Object A,Object B){
        if (A != null) {
            if (B != null) {
                //code
            }
        }
    }    
}

/* ---------------------分割线---------------------- */

class GoodExample {

    public void someMethod(Object A,Object B){
        if (A != null && B != null) {
            //code
        }
    }    
}

No.5: remove one-time temporary variable
lives we often use disposable chopsticks, this is the destruction of trees. However, in the program among the one-time temporary variables not only for the performance of small violence, it is a desecration of the code readability. Therefore, we need some one-off temporary variables surgery.
Small example

class BadExample {
    
    private int i;

    public int someMethod(){
        int temp = getVariable();
        return temp * 100;
    }
    
    public int getVariable(){
        return i;
    }    
}

/* ---------------------分割线---------------------- */

class GoodExample {

    private int i;

    public int someMethod(){
        return getVariable() * 100;
    }
    
    public int getVariable(){
        return i;
    }    
}

No.6: elimination of the parameter list is too long
for some of the parameters passed a large number of methods for the pursuit of the code neat program ape, is unacceptable. We can try to encapsulate the parameters passed to the method as an object, so as to remove long list of parameters. In most cases, when you try to find such an object, it is often already exist, so in most cases, we do not need to do extra work.
Small example

class BadExample {
    
    public void someMethod(int i,int j,int k,int l,int m,int n){
        //code
    }    
}

/* ---------------------分割线---------------------- */

class GoodExample {

    public void someMethod(Data data){
        //code
    }    
}

class Data{
    
    private int i;
    private int j;
    private int k;
    private int l;
    private int m;
    private int n;
  //getter&&setter    
}

No.7: extract or class inheritance hierarchy constants
of this reconstruction purpose is to eliminate some of the magic number or string constants, etc., the magic number of disadvantages arising from Needless to say, it can lead people to the program intention to create confusion. As for the elimination of the type of string constants, etc., more benefits that convenient maintenance. Because we only need to modify a constant, you can complete all modifications to the program code that uses the constant of.
Incidentally, such a situation similar to the most common and is the base class Action, these constants INPUT, LIST, SUCCESS like extraction.
Small example

class BadExample {
    
    public void someMethod1(){
        send("您的操作已成功!");
    }
    
    public void someMethod2(){
        send("您的操作已成功!");
    }
    
    public void someMethod3(){
        send("您的操作已成功!");
    }
    
    private void send(String message){
        //code
    }
}

/* ---------------------分割线---------------------- */

class GoodExample {
    
    protected static final String SUCCESS_MESSAGE = "您的操作已成功!";

    public void someMethod1(){
        send(SUCCESS_MESSAGE);
    }
    
    public void someMethod2(){
        send(SUCCESS_MESSAGE);
    }
    
    public void someMethod3(){
        send(SUCCESS_MESSAGE);
    }
    
    private void send(String message){
        //code
    }    
}

No.8: Let class provides methods should provide a
lot of times, we often operate most of the properties of a class to obtain a final result we want. This time, we should make this class do what it should do, should not allow us to do on its behalf. And most of the time, this process will eventually become a source of duplicate code.
Small example

class BadExample {
    
    public int someMethod(Data data){
        int i = data.getI();
        int j = data.getJ();
        int k = data.getK();
        return i * j * k;
    }
    
    public static class Data{
        
        private int i;
        private int j;
        private int k;
        
        public Data(int i, int j, int k) {
            super();
            this.i = i;
            this.j = j;
            this.k = k;
        }

        public int getI() {
            return i;
        }
        
        public int getJ() {
            return j;
        }
        
        public int getK() {
            return k;
        }        
    }    
}

/* ---------------------分割线---------------------- */

class GoodExample {
    
    public int someMethod(Data data){
        return data.getResult();
    }
    
    public static class Data{
        
        private int i;
        private int j;
        private int k;
        
        public Data(int i, int j, int k) {
            super();
            this.i = i;
            this.j = j;
            this.k = k;
        }

        public int getI() {
            return i;
        }
        
        public int getJ() {
            return j;
        }
        
        public int getK() {
            return k;
        }
        
        public int getResult(){
            return i * j * k;
        }        
    }    
}

No.9: Split lengthy class
this technique is actually part of a very useful skill, but because of its relatively high degree of difficulty. For this technique, most of the time, the focus should split a class focused on the properties of the class above. Two batches split out property can be logically separate, and in which the code, using two batches were concentrated attributes are also among certain methods. If there are really some attributes are present in two batches inside the split method, it can be solved by this manner dependent parameter transfer.
Split the class is a relatively large project, after all, a category often has been used in a program with a lot of class, so the difficulty of the reconstruction is quite large, we must be careful, and do adequate testing.
No.10: extraction inheritance hierarchy to duplicate the properties and methods of the parent class
most of the time this technique requires sufficient judgment, many times, this is actually moving in the template method pattern process. Often this type of reconstruction will not be a small project, so this one is similar to the reconstruction of the ninth, we need adequate care and testing. But also enough to confirm, these extracts to the parent class property or method, should be the common subclass of time before you can use this technique.

Conclusion

These are only a performance optimization aspects of Java programming, most of them are trade-offs in performance optimization time, efficiency, and other aspects of the code hierarchy, their pros and cons, do not put the above content as a dogma, maybe some of us actually work applies some NA, but also look right trade-offs based on the actual scene work, learn and use, flexibility is appropriate.

Guess you like

Origin blog.csdn.net/mcsbary/article/details/90481170