Java performance tuning of the program to "fly" up -Java code optimization

Code optimization objectives are:

1, reducing the volume of code

2, to improve the efficiency of the code to run

Code optimization details

 

1, the class designated as far as possible, the final modifier method

 

With the final modifier class is not derived. In the Java core API, there are many examples of final applications, such as java.lang.String, the entire class are final. Specify the final qualifier for the class allows the class can not be inherited, designated as ways to make the final modifier methods can not be overridden. If a class as final, the class of all methods are final. Java compiler will look for opportunities within the final with all methods, inline significant role for enhancing the operational efficiency of Java, refer to the specific Java runtime optimization. This can improve the performance by an average of 50%.

 

2, try to reuse objects

 

It should be used StringBuilder / StringBuffer place especially if a String object, there is connected the string. Since Java Virtual Machine not only takes time to generate the object, the future may also need to spend time on these objects for garbage collection and disposal, therefore, generate too many objects will bring great impact to the performance of the program.

 

3, try to use local variables

 

Delivery method call parameters and temporary variables created in the call are stored in the stack faster, other variables, such as static variables, instance variables, etc., are created on the heap, slower speed. In addition, the stack variables created with the method of operation is completed, the content is gone, no additional garbage collection.

 

4, close the flow

 

Java programming, database connections, be careful when I / O stream operations, after use, promptly shut down to release resources. Because of these large objects operation will cause large overhead systems, the slightest mistake will lead to serious consequences.

 

5, to minimize the double counting of the variables

 

A clear concept, method calls, even if the method is only one sentence, there are also consumed, including the creation of a stack frame to protect the site when calling the method, the recovery site when finished calling methods. So, for example, the following operations:

 

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

{...}

 

Recommended alternatives:

 

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

{...}

 

In this way, list.size () a lot of time, reducing the consumption of a lot

6, lazy loading strategy as far as possible, that is only created when needed

 

E.g:

 

 

String str = "aaa";

if (i == 1)

{

  list.add(str);

}

 

Recommended alternatives:

 

if (i == 1)

{

  String str = "aaa";

  list.add(str);

}

 

7, abnormal caution

 

Abnormal detrimental to performance. An exception is thrown first to create a new object, Throwable constructor function call interface local synchronization method named fillInStackTrace () is, fillInStackTrace () method to check the stack to collect information call tracking. As long as there is an exception is thrown, Java virtual machine must adjust the call stack, because a new object is created in the process. An exception can only be used for error handling, it should not be used to control program flow.

 

8. Do not try to use in the loop ... catch ..., should put it on the outermost

 

According to the views raised by netizens, which I think is questionable

 

9, if the content length is estimated to be added to the bottom set of an array manner, the tools specify the initial length

 

Such as ArrayList, LinkedLlist, StringBuilder, StringBuffer, HashMap, HashSet, etc., to StringBuilder example:

 

(1) StringBuilder () // default space allocation of 16 characters

(2) StringBuilder (int size) // default space allocation size characters

(3) StringBuilder (String str) // default allocation of 16 characters + str.length () characters space

 

By class (referred to herein as just above the StringBuilder) constructor to set its initial capacity, which can significantly improve performance. For example StringBuilder bar, length indicates the number of characters in the current StringBuilder can hold. Because the time when StringBuilder reached maximum capacity, it will itself increase the current capacity of 2 plus 2 times, whenever StringBuilder reached its maximum capacity, it will have to create a new character array and then the old character copy the contents of the array to a new array of characters - this is a very cost operational performance. Imagine, if you can estimate the character array to store about 5000 characters without specifying the length of the power of 2 closest to 5000 is 4096, a time of expansion plus 2 regardless, then:

 

(1) On the basis of the 4096, 8194 and then apply a character array size, add up to the equivalent of a filed 12290 character array size, if a start can specify the size of the character array 5000, saving more than doubled Space

 

(2) the original character 4096 characters copied to the new array to

 

In this way, a waste of memory space and reduce the efficiency of the code. So, to the underlying array in order to achieve the set of tools to set a reasonable initial capacity is not wrong, it will bring immediate results. However, note that this array as HashMap to achieve the set list is +, do you estimate the initial size and the size of the set, like, just because the possibility of a connection object on a table is almost zero. Recommended to set the initial size N-th power of 2, if it is estimated that there are 2,000 elements provided new HashMap (128), new HashMap (256) may be used.

 

10, when copying large amounts of data using System.arraycopy () command

 

11, shift operations using multiplication and division

 

E.g:

 

for (val = 0; val < 100000; val += 5)

{

  with a = 8 *;

  b = val / 2;

}

 

The shift operation can greatly improve performance, because in the bottom of the computer, the operating position is the most convenient, fastest, it is proposed amended as follows:

 

for (val = 0; val < 100000; val += 5)

{

  a = val << 3;

  b = val >> 1;

}

 

Shift operation may be fast, but might make the code less well understood, it is best to add the appropriate comments.

 

12, the inner loop do not continue to create an object reference

 

E.g:

 

for (int i = 1; i <= count; i++)

{

    Object obj = new Object();    

}

 

This practice can lead to memory have copies Object object reference count, count a lot, then it is the cost of memory, it is recommended to read:

 

Object obj = null;

for (int i = 0; i <= count; i++)

{

    obj = new Object();

}

 

In this case, only one memory Object object reference, each new Object () when, Object object reference point to different Object nothing, but only a memory, thus greatly save memory space up.

 

Only 13, based on considerations of efficiency and type checking, array should be used as much as possible, we can not determine the size of the array using ArrayList

 

14, to make use of HashMap, ArrayList, StringBuilder, unless the thread security needs, or do not recommend using Hashtable, Vector, StringBuffer, after three synchronization mechanisms which led to the use of performance overhead

 

15, do not declare the array as public static final

 

Because this is meaningless, it just defines a reference for the static final, or the contents of the array can be freely changed, the array is declared as a public security vulnerability, which means that the array can be changed by external class

 

16, as far as possible in the case of a suitable embodiment with a single

 

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, a single case mainly applies to the following three aspects:

 

(1) control the use of resources, synchronize concurrent access to resources controlled by a thread

 

(2) generating the control instance in order to save resources

 

(3) control shared data, at no direct association, so to achieve between multiple processes or threads unrelated communication

 

17, try to avoid using static random variable

 

You know, when the reference to an object is defined as a static variable, then gc usually does not reclaim the heap memory occupied by objects, such as:

 

public class A

{

    private static B b = new B();  

}

 

At this static variable b of the life cycle of the same class A, class A if not uninstalled, then the B object reference point B will be permanent memory, until the program is terminated.

 

18, the timely removal session is no longer needed

 

To clear the session is no longer active, many application servers have the default session timeout time, usually 30 minutes. When the application server need to preserve more conversation, if insufficient memory, the operating system will transfer part of the data to disk, the application server may also be based on MRU (most recently the most frequently used) algorithm is the part of inactive sessions dump to disk, and may even be thrown out of memory exception. If the session is to be dumped to disk, it must first be serialized, large-scale cluster, an object is serialized costs are very expensive. Therefore, when the session is no longer needed, it should promptly call the HttpSession invalidate () method to clear conversation.

 

19, a set of interfaces to achieve RandomAccess such as ArrayList, you should use the most common for loop instead of foreach loop to iterate

 

This is the JDK recommended to the user. JDK API for interpretation RandomAccess interface are: to achieve RandomAccess interface is used to indicate that they support fast random access, the main purpose of this interface is to allow generic algorithms to alter their behavior in order to apply it to a random or sequential access lists can provide a good performance. Practical experience shows RandomAccess interface class instance, if a random access using a normal cycle efficiency will be higher than for using foreach loop; Conversely, if sequential access, the use of higher efficiency will Iterator. Code similar to the following can be determined:

 

if (list instanceof RandomAccess)

{

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

}

else

{

    Iterator<?> iterator = list.iterable();

    while (iterator.hasNext()){iterator.next()}

}

 

The principle underlying the foreach loop iterators Iterator, see Java syntax sugar 1: foreach loop variable length parameters and principles. So after the word "Conversely, if it is sequential access, use Iterator will be higher efficiency" means that class instances sequential access, use a foreach loop to iterate.

 

20, an alternative synchronization method using a synchronization code blocks

 

This synchronized lock in a multithreaded module in a text block method has been very clear, unless it can determine an entire methods are needed to synchronize, otherwise make use of synchronized block, avoid those that do not require synchronization code also synchronized, affecting the efficiency of code execution.

 

21, the constant is declared as static final, and in upper case named

 

Thus during compilation you can put the content into the constant pool, to avoid generating a constant calculated value during operation. In addition, the constant name in uppercase name can easily distinguish between variable and constant

 

22, do not create some objects do not use, do not import some classes do not use

 

This is meaningless, if the code appears in "The value of the local variable i is not used", "The import java.util is never used", then please remove these unwanted content

 

23, the program is running to avoid using reflection

 

Please see the reflection. Java reflection is to provide the user with a very powerful, powerful often means inefficient. Not recommended, especially the frequent use of reflection in the program is running, especially Method invoke method, if indeed there is necessary a suggestive approach is reflected those classes need to load at the time of project start by reflecting instance of an object and placed in memory - users only get the care and the fastest response time to end the interaction, do not care how long it started to spend time on the end of the project.

 

24, using a database connection pooling and thread pooling

 

Both pools are objects for reuse, the former can avoid frequent opening and closing connections, which can avoid frequently create and destroy threads

 

25, using the buffered input and output streams IO operation

 

Buffered input and output streams, i.e. BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream, which can greatly enhance the efficiency of IO

 

26, the order of insertion and are more random access scenario using the ArrayList, and remove the intermediate element inserted more scenes using LinkedList

 

This understanding of the principles of ArrayList and LinkedList know

 

27, do not let the public process has too many parameter

 

Methods public method that is provided externally, if too much parameter to these methods, then there are two main disadvantages:

 

1, violated the idea of ​​object-oriented programming, Java and stress everything is an object, too many formal parameters, and object-oriented programming ideas do not fit

 

2, too many parameters will inevitably lead to an increase in error probability method call

 

As for the "too much" refers to the number, 3,4 bar. For example, we write a insertStudentInfo using JDBC methods, there are 10 fields to be inserted as the student information Student table, these 10 parameters can be encapsulated in an entity class, as a method of insert shape parameter

 

28, string variables and string constants equals the time constant string EDITORIAL

 

This is a relatively common tips, and if there is the following code:

 

String str = "123";

if (str.equals("123"))

{

    ...

}

 

Proposed changes are:

 

String str = "123";

if ("123".equals(str))

{

    ...

}

 

Do so mainly to avoid null pointer exception

 

29, please know that in java if (i == 1) and if (1 == i) there is no difference, but the reading habits of speaking, with the former being

 

Usually someone asked, "if (i == 1)" and "if (1 == i)" there is no difference, from which C / C ++ talk.

 

In C / C ++ in, "if (i == 1)" determination condition is satisfied, 0 is the non-zero-based, 0 represents false, nonzero if true, if there is such a code:

 

int i = 2;

if (i == 1)

{

    ...

}

else

{

    ...

}

 

C / C ++ Analyzing "i == 1" is not satisfied, it represents 0, i.e. false. but if:

 

int i = 2;

if (i = 1)

{

    ...

}

else

{

    ...

}

 

In case a programmer is not careful, the "if (i == 1)" written "if (i = 1)", so there will be problems. If i is within the assigned one, if non-zero determines the contents inside, true is returned, but obviously i is 2, the comparison value is 1, it should return false. In this case the development of C / C ++ in is likely to occur and can lead to some incomprehensible error occurs, so, in order to avoid developers in an if statement incorrect assignment, suggested that if the statement is written as:

 

int i = 2;

if (1 == i)

{

    ...

}

else

{

    ...

}

 

Thus, even if developers do not accidentally wrote "1 = i", C / C ++ compiler can also check out the first time, because we can be assigned to a variable i is 1, but can not assign a constant 1 i.

 

However, in Java, C / C ++ this syntax "if (i = 1)" is impossible, because once wrote this syntax, Java will compile error "Type mismatch: can not convert from int to boolean . " However, despite Java's "if (i == 1)" and "if (1 == i)" there is no difference in semantics, but the reading habits of speaking, with the former would be better.

 

30. Do not use the toString () method of the Array

 

Look at what the array using toString () print out are:

 

public static void main(String[] args)

{

    int[] is = new int[]{1, 2, 3};

    System.out.println(is.toString());

}

 

The result is:

 

[I@18a992f

 

 

Intention is to print out the contents of the array, there may be empty because the array reference is caused by a null pointer exception. But while () does not make sense for an array toString, but the collection toString () can print out the contents of the collection inside, because the parent AbstractCollections collection <E> rewriting the toString Object () method.

 

32, do not do down casts the basic data type out of range

 

This will not get the desired results:

 

public static void main(String[] args)

{

    long l = 12345678901234L;

    you i = (you) l;

    System.out.println(i);

}

 

We might expect a few of them, but the result is:

 

1942892530

 

explain. Java is 8 bytes long in the 64-bit, so 12345678901234 in the computer that should be:

 

0000 0000 0000 0000 0000 1011 0011 1010 0111 0011 1100 1110 0010 1111 1111 0010

 

Int type is a 4-byte 32-bit, 32-bit is removed from the front above the lower string of binary data is:

 

0111 0011 1100 1110 0010 1111 1111 0010

 

The string of binary represented as decimal 1,942,892,530, so the content is output on the console above us. In this example also the way to two conclusions:

 

1, the default data type is an integer int, long l = 12345678901234L, this number is beyond the scope of the int, so there is a final L, it indicates that this is a long type number. By the way, floating-point default type is double, so the definition of float time to write "" float f = 3.5f "

 

2, then write an "int ii = l + i;" will be given as long + int is a long, int can not be assigned to

 

33, the common data collection class is not used must be timely remove off

 

If a collection is public (that is not the way inside the property), then the set of elements inside are not automatically released, because there is always a reference point to them. So, if some of the data does not use public collection inside out rather than to remove them, it will cause the public collection is increasing, so that the system has a memory leak problems.

 

34, the basic data types into a string of basic data types .toString () is the fastest way, String.valueOf (data), followed by data + "" slowest

 

The basic data types into a generally three ways, I have a data type Integer i, you can use i.toString (), String.valueOf (i), i + "" three ways, how efficient are three ways to see a test:

 

public static void main(String[] args)

{

    int loop time = 50000;

    Integer i = 0;

    long startTime = System.currentTimeMillis();

    for (int j = 0; j < loopTime; j++)

    {

        String str = String.valueOf(i);

    }    

    System.out.println("String.valueOf():" + (System.currentTimeMillis() - startTime) + "ms");

    startTime = System.currentTimeMillis();

    for (int j = 0; j < loopTime; j++)

    {

        String str = i.toString();

    }    

    System.out.println("Integer.toString():" + (System.currentTimeMillis() - startTime) + "ms");

    startTime = System.currentTimeMillis();

    for (int j = 0; j < loopTime; j++)

    {

        String str = i + "";

    }    

    System.out.println("i + \"\":" + (System.currentTimeMillis() - startTime) + "ms");

}

 

Operating results as follows:

 

String.valueOf():11ms

Integer.toString():5ms

i + "":25ms

 

So we encountered after the basic data types into a String of time, giving priority to the use of toString () method. As for why, it is simple:

 

1, String.valueOf () method calls the underlying Integer.toString () method, but the pre-determined short call

 

2, Integer.toString () method is not to say, direct call

 

3, i + "" bottom StringBuilder implemented using a first append method by stitching, and then toString () method takes a string

 

Comparative down three, obviously 2 fastest, followed by 1, 3 slowest

 

35, using the most efficient way to traverse Map

 

There are many ways to traverse Map, usually the scene we need is to traverse the Map Key and Value, it is recommended to use, most efficient way is:

 

public static void main(String[] args)

{

    HashMap<String, String> hm = new HashMap<String, String>();

    hm.put("111", "222");

 

    Set<Map.Entry<String, String>> entrySet = hm.entrySet();

    Iterator<Map.Entry<String, String>> iter = entrySet.iterator();

    while (iter.hasNext())

    {

        Map.Entry<String, String> entry = iter.next();

        System.out.println(entry.getKey() + "\t" + entry.getValue());

    }

}

 

If you just want to traverse about this key value Map, then use "Set <String> keySet = hm.keySet ();" Some would be more appropriate

 

36, to close the resource () is recommended operated separately

 

Mean, for example, I have such a piece of code:

 

try

{

    XXX.close();

    YYY.close();

}

catch (Exception e)

{

    ...

}

 

Proposed changes are:

 

try

{

    XXX.close();

}

catch (Exception e)

{

    ...

}

try

{

    YYY.close();

}

catch (Exception e)

{

    ...

}

 

Although some trouble, he was able to avoid resource leaks. We want, if not modified code, in case XXX.close () throw an exception, then entered the catch block, YYY.close () will not be executed, YYY this resource will not be recovered until occupied with such a code is more than one, is likely to cause resource handle leak. But after the following wording be changed, we ensure that in any case will be XXX and YYY close out

 

37, for the first use or after use ThreadLocal must first remove

 

The current base all projects using the thread pool, which is very good, you can dynamically configure the number of threads, the thread can be reused.

 

However, if you use a ThreadLocal to the project, you must remember to remove it before use or after use. This is because the above-mentioned thread pool thread to do is reuse, which means that the code running in the process, a thread after use, and will not be destroyed but a wait of use. We look at the Thread class, hold ThreadLocal.ThreadLocalMap of reference:

 

/* ThreadLocal values pertaining to this thread. This map is maintained

 * by the ThreadLocal class. */

ThreadLocal.ThreadLocalMap threadLocals = null;

 

ThreadLocal.ThreadLocalMap thread does not mean the destruction of threads on the set of the data still exists, then the next one thread Thread reuse this time, it is possible to get the threads set of data rather than the content they want.

 

This problem is very subtle, this causes once error occurs, there is no relevant experience or no solid foundation is very difficult to find the problem, so we should pay attention to this point, which will give you a lot of subsequent reduction of the workload when writing code.

 

postscript

 

Good code from each little bit of optimization, attention to every detail, not only can improve the efficiency program, the same can avoid a lot of unanswered questions.

 

This article is reproduced in:

www.cnblogs.com/xrq730/p/4865416.html

Guess you like

Origin www.cnblogs.com/zhengjinsheng/p/11206224.html