Help to improve the performance of Java code tips

Foreword

Performance of the program are directly affected by the quality of the code. The practice focuses on tips and write some code. Although seem trivial programming skills but potentially enhance system performance exponentially, so it is worthy of attention.

Abnormal caution

In Java development, often using try-catch error trapping, but try-catch statement in terms of system performance is very bad. Although a try-catch, we can not perceive the loss of her performance brought, but once the try-catch statement is used in circulation or traverse the body, it will bring great harm to the system performance.

The following is an example of code that try-catch applied to the loop body:

    @Test
    public void test11() {

        long start = System.currentTimeMillis();
        int a = 0;
        for(int i=0;i<1000000000;i++){
            try {
                a++;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println("useTime:"+useTime);

    }

The result of this is to run the above code:

useTime: 10

The following is a try-catch to move the code vitro cycle, then performance improves nearly half. as follows:

    @Test
    public void test(){
        long start = System.currentTimeMillis();
        int a = 0;
        try {
            for (int i=0;i<1000000000;i++){
                a++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println(useTime);
    }

operation result:

useTime: 6

Use local variables

Delivery method call parameters and temporary variables created in the call are stored in the stack (Stack), fast. Other variables, such as static variables, instance variables, etc., are in the heap (Heap) to create, slowly.

The following is a local variable code calculation:

   @Test
    public void test11() {

        long start = System.currentTimeMillis();
        int a = 0;
        for(int i=0;i<1000000000;i++){
            a++;
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println("useTime:"+useTime);

    }

operation result:

useTime: 5

The static class variables replace local variables:

    static int aa = 0;
    @Test
    public void test(){
        long start = System.currentTimeMillis();

        for (int i=0;i<1000000000;i++){
            aa++;
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println("useTime:"+useTime);
    }

operation result:

useTime: 94

By running the above results twice, you can see the speed of access to the local variables is much higher than the class member variables.

Bit multiplication and division operations instead of

In all operations, the bit operation is most efficient. Thus, try to replace part of the bit arithmetic operation, to increase the operating speed of the system. The most typical is optimized for integer multiplication and division.

The following is a use of an arithmetic operation code:

    @Test
    public void test11() {

        long start = System.currentTimeMillis();
        int a = 0;
        for(int i=0;i<1000000000;i++){
            a*=2;
            a/=2;
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println("useTime:"+useTime);
    }

operation result:

useTime: 1451

The multiplication and division in the loop body to equivalent bit operation code is as follows:

    @Test
    public void test(){
        long start = System.currentTimeMillis();
        int aa = 0;
        for (int i=0;i<1000000000;i++){
            aa<<=1;
            aa>>=1;
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println("useTime:"+useTime);
    }

operation result:

useTime: 10

Performed on two pieces of code are identical functions, in each cycle, will be multiplied by the integer 2, and dividing by two. But the results of time-consuming operation difference is very large, so-bit computing efficiency is still obvious.

Extraction expression

In the software development process, programmers can easily make the code intentionally or unintentionally, do some "duplication", in most cases, due to the high speed operation of the computer, the "duplication of effort" does not constitute much of a threat on performance, However, if you want to play the system performance to the limit, extract the "duplication of effort" quite meaningful.

The following code example, two arithmetic is performed:

    @Test
    public void testExpression(){
        long start = System.currentTimeMillis();
        double d = Math.random();
        double a = Math.random();
        double b = Math.random();
        double e = Math.random();

        double x,y;
        for(int i=0;i<10000000;i++){
            x = d*a*b/3*4*a;
            y = e*a*b/3*4*a;
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println("useTime:"+useTime);

    }

operation result:

useTime: 21

A closer look can find two exactly the same calculation expression of the second half, it also means that in each cycle, part of the same expression is recalculated.

So to improve it, it becomes like the following:

    @Test
    public void testExpression99(){
        long start = System.currentTimeMillis();
        double d = Math.random();
        double a = Math.random();
        double b = Math.random();
        double e = Math.random();

        double p,x,y;
        for(int i=0;i<10000000;i++){
            p = a*b/3*4*a;
            x = d*p;
            y = e*p;
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println("useTime:"+useTime);
    }

operation result:

useTime: 11

We can see the effect of specific optimization by the results.

Similarly, if the need to perform a time-consuming operation in a certain cycle, and the body of the loop, the execution result is always unique, extracorporeal circulation should be extracted.

For example the following code:

for(int i=0;i<100000;i++){
    x[i] = Math.PI*Math.sin(y)*i;
}

Should be modified to the following code:

// extract complex business logic processing result is fixed to the extracorporeal circulation 
Double P * = Math.PI Math.sin, (Y);
 for ( int I = 0; I <100000; I ++ ) { 
    X [I] = P * I ; 
}

Use arrayCopy ()

Array replication is a high frequency of use features, JDK provides an efficient API to implement it.

/**
     * @param      src      the source array.
     * @param      srcPos   starting position in the source array.
     * @param      dest     the destination array.
     * @param      destPos  starting position in the destination data.
     * @param      length   the number of array elements to be copied.
     * @exception  IndexOutOfBoundsException  if copying would cause
     *               access of data outside array bounds.
     * @exception  ArrayStoreException  if an element in the <code>src</code>
     *               array could not be stored into the <code>dest</code> array
     *               because of a type mismatch.
     * @exception  NullPointerException if either <code>src</code> or
     *               <code>dest</code> is <code>null</code>.
     */
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

If you need to copy an array in your application, you should use this function, rather than trying to achieve.

Exemplified below:

    @Test
    public void testArrayCopy(){
        int size = 100000;
        int[] array = new int[size];
        int[] arraydest = new int[size];

        for(int i=0;i<array.length;i++){
            array[i] = i;
        }
        long start = System.currentTimeMillis();
        for (int k=0;k<1000;k++){
            //进行复制
            System.arraycopy(array,0,arraydest,0,size);
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println("useTime:"+useTime);
    }

operation result:

useTime: 59

Correspondingly, if the program to achieve an array of their own copy, the equivalent code is as follows:

    @Test
    public void testArrayCopy99(){
        int size = 100000;
        int[] array = new int[size];
        int[] arraydest = new int[size];

        for(int i=0;i<array.length;i++){
            array[i] = i;
        }
        long start = System.currentTimeMillis();
        for (int k=0;k<1000;k++){
            for(int i=0;i<size;i++){
                arraydest[i] = array[i];
            }
        }
        long useTime = System.currentTimeMillis()-start;
        System.out.println("useTime:"+useTime);
    }

operation result:

useTime: 102

Effect can be seen by the results.

Since System.arraycopy () function is a native functions, performance is generally superior to native functions of normal functions. For performance reasons only, at the time of program development, you should call the native function as possible.

 

 

 

Back will be continuously updated. . .

Guess you like

Origin www.cnblogs.com/jimoer/p/10787672.html