Java Performance Tuning section details

In the JAVA program, most of the causes of performance problems is not the JAVA language, but the program itself. Develop good coding practice is very important, can significantly improve the performance of the program.

 

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

First, control the use of resources by thread synchronization to control concurrent access to resources;

Second, control generates instance, in order to save resource;

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

2. Try to avoid using static random variable

When an object is defined as a static variable is referenced, then the GC does not reclaim the object is usually occupied by memory, 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 frequent method calls, circulating 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, within the range that we can control, maximize reuse of objects , 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), a move that 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;

}

Correction:

class DAF_fixed {

final public void setSize (int size) {

_size = size;

}

private int _size;

}

5. make use of local variables

Delivery method call parameters and temporary variables created in the call are stored in the stack (Stack), the faster; other variables, such as static variables, instance variables are created in the heap (Heap), slow .

6. Try to deal with two basic types of packaging type and place of use

Although the basic types and the type of packaging during use can be interchangeable, but they both memory area is generated completely different basic types of data processing are generated and processed in the stack, a package type object in the heap generating 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, a method 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. Therefore, to minimize Synchronize method, and the method should be used instead of the sync block synchronization.

9. Try not to use finalize method

In fact, the clean-up resources in finalize method is done 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 again choose to use finalize methods of resource clean-up will lead to a greater burden on GC, process efficiency worse.

10 make use of the basic data types in place of object

Str = String "hello";
1
above in this way will create a "hello" string, and JVM character string buffer pool will be cached;

String str = new new String ( "Hello");
. 1
at this time to create the program in addition to 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. Multithreading did not occur in the thread-safe 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. The calculation is repeated to minimize the variables

Such as:

for (int I = 0; I <list.size (); I ++)
. 1
should read:

for (I = 0, len = list.size () int; I <len; I ++)
. 1
and in the circulation should avoid using complex expressions, in a loop, the loop condition is repeatedly calculated, if expressed without using a complicated type, the value of the same cycling conditions, the program will run faster.

14. Try to avoid unnecessary creation

Such as:

A a = new A();

if(i==1){

list.add(a);

}

It should read:

if(i==1){

A a = new A();

list.add(a);

}

15. The release of resources as far as possible in the finally block

Used in the program to resources should be released, to avoid resource leaks, which 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. The shift instead to make use of 'a / b' operation

"/" Is a high cost of operation, shift operation will be faster and more efficient

Such as:

int num = a / 4;

int num = a / 8;

should read:

int num = a >> 2;

int num = a >> 3;

but it should be noted that using a shift add comments, because the shift operation is not intuitive and more difficult to understand.

17. The shift instead to make use of 'a * b' operation

Likewise, for the '*' operator, using the operation of the shift will be faster and more efficient

Such as:

int num = a * 4;

NUM = A *. 8 int;
. 1
2
. 3
should read:

int num = a << 2;

<< A. 3 NUM = int;

18. A possible to determine the capacity of 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:

StringBuffer buffer = new StringBuffer(1000);

19. The earliest possible release of useless object reference

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;

}

The above this is not necessary, the method performed with the completion test (), the program references the variable obj scope ended. But if it is changed to the following:

Public void test(){

Object obj = new Object();

……

Obj=null;

// time-consuming, consuming memory operations; or call the time-consuming and memory-intensive method

……

}

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

20. Try to avoid using two-dimensional array

Two-dimensional data memory space occupied by much more than a one-dimensional array, probably more than 10 times.

21. 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 it is frequent tens, hundreds of millions of calls will cost a lot of resources, if you do need to call frequently split, you can consider using the apache StringUtils.split (string, char), frequently split can be cached results.

22. ArrayList & LinkedList

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

23. Try to use System.arraycopy () instead of an array by copying cycle

System.arraycopy () by circulating faster than to duplicate the array has more.

24. Try to cache frequently used objects

Frequently used as an object cache, 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, we recommend using some third-party open source tools such as EhCache , Oscache cache, they basically have achieved a FIFO / FLU such as caching algorithms.

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

26. Abnormal caution

When you create an exception, you need to collect a stack trace (stack track), this is an exception stack trace is used to describe 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, the good news is not abnormal capture overhead, 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 exceptions, 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.

27. Try to reuse objects

In particular when a String object, using concatenation occurs StringBuffer place, not only because the system takes time to generate the object, 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.

28. Do not repeat initialize variables

By default, when the class constructor call, 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 logical 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. For example initXXX (), since a direct call assignment may be because the method has not been initialized and the class pointer exception shorting, such as: public int state = this.getState ().

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

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

31. The excessive amount of memory consumed by the system will create an object, 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.

32. When using a synchronization mechanism, the method should be used instead of the sync block synchronization.

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

34. It is set by the constructor StringBuffer initial capacity can significantly improve performance

StringBuffer default capacity is 16, when the maximum capacity StringBuffer capacity, it will increase the capacity of their current times of 2 + 2, i.e. 2 * n + 2. Whenever StringBuffer reach its maximum capacity, it will 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!

35. 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, and then delete, such as int index = indexOf (obj); vector.remove (index).

38. no new keyword to create an instance of an object

When creating a new instance of a class using keywords, all constructors are constructor is invoked automatically chain. But if an object implements the Cloneable interface, we can call its 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();

}

Code improved using clone () method:

private static Credit BaseCredit = new Credit();

public static Credit getNewCredit()

{

return (Credit)BaseCredit.clone();

}
39. Do not declare the array as: public static final

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

}

Using the extracted hash value corresponding Entry comparison result obtained, direct access to the key and value achieved after the entry of the value.

Use 41. array (array) and the ArrayList

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

42. Single-threaded should use HashMap, ArrayList, unless absolutely necessary, otherwise it is not recommended to use HashTable, Vector, they use a synchronization mechanism, and reduce performance.

43. StringBuffer, StringBuilder difference is that: a 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 StringBuilder class, because it supports all of the same operation, but because it does 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.

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

45. The use of high specific analog interfaces use efficiency, but reduces the structural flexibility, but modern IDE can solve this problem.

46. ​​Consider using static methods, if you do not need to go outside to access the object, then make your way to become a static method. It will be faster to call, because it does not require a virtual function-oriented table. It is also a good practice, because it tells you how to distinguish the nature of the process, calling this method does not change the state of the object.

47. Avoid using internal GET, SET method as possible.

48. Avoid enumeration, the use of floating point numbers.

Here are some examples of practical optimization:
one, avoiding the use of complex expressions in loop condition

In the case of not optimizing compiler, in a loop, loop condition is evaluated again quickly, without the use of complex expressions, the value of the same cycling conditions, the program will run. example:

java.util.Vector import;

class CEL {

void method (Vector vector) {

for (int i = 0; i < vector.size (); i++) // Violation

; // ...

}

}
Correction:

class CEL_fixed {

void method (Vector vector) {

int size = vector.size ()

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

; // ...

}

}

Second, for the 'Vectors' and 'Hashtables' define the initial size

Vector expand the size of the JVM is 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:

java.util.Vector import;

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 );

three, finally block off Stream

Program to use 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.

Fourth, the use of 'System.arraycopy ()' instead of the array by copying cycle

example:

public class IRB

{

void method () {

int[] array1 = new int [100];

for (int i = 0; i < array1.length; i++) {

array1 [i] = i;

}

int[] array2 = new int [100];

for (int i = 0; i < array2.length; i++) {

array2 [i] = array1 [i]; // Violation

}

}

}

Correction:

public class IRB

{

void method () {

int[] array1 = new int [100];

for (int i = 0; i < array1.length; i++) {

array1 [i] = i;

}

int[] array2 = new int [100];

System.arraycopy(array1, 0, array2, 0, 100);

}

}

V. allow access instance variables within the 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;

}

Correction:

class DAF_fixed {

final public void setSize (int size) {

_size = size;

}

private int _size;

}

Six, for 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.

Seven, when the sum of the string, use '' instead of "", if the string is one character, then

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'

}

}

These are only optimize performance 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 apply, some NA, but also hope to choose according to the actual scene work, learn and use, flexibility is appropriate.
---------------------

Original: https: //blog.csdn.net/qq_42894896/article/details/82256770

Guess you like

Origin www.cnblogs.com/dayandday/p/11028127.html