Su small warm java performance optimization

Code optimization, a very important issue. Some people may feel useless, some small places there is nothing to modify, change and do not change what impact the efficiency of the code for it? The problem is what I consider, like the sea, like whales inside, it eats a Shrimps useful? Useless, however, after more than one Shrimps eat whale was fed up.

Code optimization is the same, if not the BUG project focusing on line as soon as possible, then the time may encounter, details of the code can not and deliberate; but if there is sufficient time to develop and maintain the code, this time it is necessary to consider each you can optimize the details, and one by one small optimization points accumulated for the efficiency of the code is absolutely upgrade.

Haste makes waste To reach the haste makes waste!

Code optimization objectives are:

  • Code size reduction
  • Improve the efficiency of code running

Code optimization details

1, try to use the final modifier

With the final modifier class is not derived in the Java core API, there are many examples of final application, for example Java.lang.String, the entire class are final. Specify the final qualifier for the class allows the class can not be inherited, specify the final modifier can not be rewritten to make Method method. If developed a class final, the class of all methods are final. Java compiler will look for opportunities within the final with all methods, inline great role for enhancing the operational efficiency of Java, can enhance performance by an average of 50%.

2, try to reuse objects

In particular use a String object, there should be used instead of a string StringBuilder or StringBuffer connection. 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

Passed when calling the method parameters and temporary variables are created in the call stored in the stack, faster, other variables, such as static variables, instance variables, etc., are created on the heap, slowly. 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 IO stream operation, after use, promptly shut down to release resources. Because of the overhead caused great action of these large objects, 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, is consumed, including the creation of a stack frame to protect the site when calling the method, the recovery site when finished calling the method. So, for example, the following operations:

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

Recommended alternatives:

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

In this way, a lot of list.size time, it reduces a lot of consumption.

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, call the constructor of Throwable interface, called fillInStackTrace the local synchronization method, 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 use trycatch in the loop, it should be placed in the outermost

Unless a last resort. If for no reason so written, as long as you a little senior leadership, there is a little obsessive-compulsive disorder, most probably you will curse Why write this code to the garbage.

9, can try to estimate the length of the contents to be added, the bottom layer is set as an array implemented tools specify the initial length

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

① StringBuilder // default space allocated 16 characters

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

③ StringBuider (String str) // default allocation of 16 characters + st.length character spaces

Setting initial capacity, performance can be improved significantly. For example StringBuilder, length indicates the number of characters in the current StringBuilder can hold. Because when StringBuilder reached maximum capacity, it will itself increase the current capacity of 2 plus 2 times, whenever StringBuilder only reaches its maximum capacity, it will have to create a new character array and then the old character content copied to the new array of character array - which is a very time-consuming operation performance. Imagine, if you can estimate the character array to store about 5000 characters without specifying the length, the closest power of 2 5000 4096, every expansion doubly 2 2, then:

① 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 .

② the original 4096 characters copied to the new array of characters to go.

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. Note, however, such as an array hashmap + linked list implementation of the set, do the initial estimation of the same size and the size of your set, only because of the possibility of an object on a connection 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 the command system.arraycopy

11, shift operations using multiplication and division

E.g:

int a = 0;
int b = 0;
for (int i = 0; i < 1000000000; i++){
   a = i * 8;
   b = i / 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:

int a1 = 0;
int b1 = 0;
for (int i = 0; i < 1000000000; i++){
    a1 = i << 3;
    b1 = i >> 1;
}

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

Feeling a little picky, how many cycles it all, only worse 2 milliseconds! ! !

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, when each new Object, Object Object object reference point nothing different, but only one 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 hashmap, ArrayList, stringbuilder, unless the thread security needs, it is not advisable to use hashtable, vector, stringbuffer, the latter three due to the use of synchronization mechanisms leading to the performance overhead.

15, do not talk about an array declared as public static final

16, to make use of single-mode embodiment, in a suitable case

Using the Singleton pattern can reduce the burden of load, reduce the time to load and improve the efficiency of loading, not all places are suitable for single-case model, in simple terms, the Singleton pattern is mainly applied to the following three aspects:

① control the use of resources, resource synchronization control concurrent access by threads

② generating the control instance in order to save resources

③ control data sharing, under conditions not directly related to the establishment, so that to achieve between multiple processes or threads unrelated communication

17, try to avoid using static variables

You know, when an object is defined as static, then the gc usually do not recover this heap memory occupied by the object,

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 reference point B of objects of 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 servers will have a default time-out period, typically 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 dump the inactive session 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, object serialization price is very high. Therefore, when the session is no longer needed, you should call promptly httpseesion clear the session's invalidate method.

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

Achieve RandomAccess interface 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 when to provide good performance. Practical experience shows RandomAccess interface class instance, if a random access using the higher cycle efficiency for ordinary use foreach loop, in turn, if sequential access, the use of more efficient Iterator. Similarly the code may be used for determining the following:

if (list instanceof RandomAccess){ 
    for (int i = 0; i < list.size; i++){}
}else{
    Iterator<?> iterator = list.iterable; while (iterator.hasNext){iterator.next}
}

Foreach of the underlying implementation is Iterator.

20, instead of the synchronization method using a synchronization code blocks

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

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

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

23, the program is running to avoid using reflection

Java reflection is provided by a very powerful, powerful 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 the project started by reflection instantiate an object and placed in memory - only concern the interaction of speed, without regard to the time the project started.

24, using a database connection pooling and thread pooling

The former can avoid the frequent opening and closing the connection; the latter can avoid frequent creating and destroying 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 with the ArrayList scenes, and intervening element deletion more scenes using LinkedList

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

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

Do so mainly to avoid a 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

30, do not use the array method toString

31, do not do down the mandatory transition to the underlying data type out of range

32, 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.

33, to a base type to a string, toString fastest, followed String.valueOf, Data + "" slowest

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

① String.valueOf underlying method call Integer.toString method, but before calling the judge will be short

② Integer.toString method is not to say, direct call

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

Three contrast down, obviously the fastest ②, ① followed, ③ slowest

34, using the most efficient way to traverse map

35, 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. I think, if not modified code, in case XXX.close throw an exception, then entered the block in the cath, YYY.close not be executed, YYY this resource will not be recovered, has been occupied with, so more than one code, it is possible to cause resource handle leak. But after the wording was changed to the above, ensures that in any case will be XXX and YYY close out.

Published 110 original articles · won praise 8 · views 6928

Guess you like

Origin blog.csdn.net/guorui_java/article/details/104107390