Java Program Optimization Details

Source: Internet
Author: User
Tags connection pooling finally block stack trace stringbuffer

1. Try to use a single case in the appropriate situation
Using a single example can reduce the load burden, shorten the loading time, improve the efficiency of loading, but not all places are applicable to a single case, simply speaking, the single case is mainly applicable to the following three aspects:
1). Control the use of resources, through thread synchronization to control the concurrent access of resources;
2). Control the generation of instances, in order to achieve the purpose of saving resources;
3). Control data sharing to enable communication between multiple unrelated processes or threads without establishing a direct association.

2. Try to avoid using static variables arbitrarily
It is important to know that when an object is defined as referenced by the STATAIC variable, the GC does not normally reclaim the memory that the object occupies, as
Java code
public class a{
Static b b = new B ();
}
At this point, the lifetime of static variable B is synchronized with Class A, and if Class A does not unload, the B object will reside in memory until the program terminates.

3. Try to avoid too often creating Java objects
Try to avoid the frequently called methods, loops in the new object, because the system not only takes time to create objects, but also takes time to garbage collection and processing of these objects, in the scope of our control, to maximize the reuse of objects, it is best to use basic data types or arrays to replace the object.

4. Use the final modifier as much as possible

A class with a final modifier is not derived. In the Java Core API, there are many examples of final applications, such as java.lang.String. Specifying final for the String class prevents the consumer from overwriting the length () method. In addition, if a class is final, all methods of that class are final. The Java compiler looks for the opportunity Inline (inline) for all final methods (this is related to the specific compiler implementation). This will increase the performance by an average of 50%.


5. Use local variables as much as possible
The parameters passed when the method is called and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables, instance variables, and so on, are created in the heap and are slower.

6. Try to handle the use of both the packing type and the basic type
Although wrapper types and basic types can be converted to each other during use, they produce a completely different area of memory, with basic type data generation and processing in the stack, the wrapper type being the object, and the instance being generated in the heap.
In the collection class object, there are objects that require processing for the wrapper type, and other processing advocates the use of basic types.

7. Use synchronized carefully to minimize the Synchronize method

All know that the implementation of synchronization is a great cost of overhead, and may even lead to deadlock, so try to avoid unnecessary synchronization control. When the Synchronize method is called, it locks the current object directly, and other threads cannot invoke the other methods of the current object until the method finishes executing. So the method of synchronize is as small as possible, and should try to use method synchronization instead of code block synchronization.


8. Use StringBuilder and StringBuffer for string connections whenever possible

9. Try not to use the Finalize method
In fact, it is very bad choice to put the resource cleanup in the Finalize method, because the GC workload is very large, especially when recovering Young's memory, most of which will cause the application to pause, so the choice of using the Finalize method for resource cleanup will lead to greater GC burden, Programs run less efficiently.
SPRINGMVC Integrated mybatis Framework Source code
10. Try to use basic data types instead of objects
String str = "Hello";
In this way, a "hello" string is created, and the character cache pool of the JVM also caches the string;
String str = new string ("Hello");
At this point the program, in addition to creating a string, str refers to the bottom of the string object also contains a char[] array, the char[] array is stored in turn h,e,l,l,o

11. Single thread should try to use HashMap, ArrayList

HashTable, vectors, etc. use the synchronization mechanism to reduce the performance.

12. Create HashMap as reasonable as possible
When you want to create a larger hashmap, take advantage of another constructor
Public HashMap (int initialcapacity, float loadfactor)
Avoid HashMap multiple hash refactoring, the expansion is a very cost-performance thing, in the default initialcapacity only 16, and Loadfactor is 0.75, how much capacity you need, you'd better be able to accurately estimate the best size you need, The same is true of the same hashtable,vectors.

14. Try to avoid unnecessary creation
Such as
A = new A ();
if (i==1) {list.add (a);}
should be changed to
if (i==1) {
A = new A ();
List.add (a);}

15. Dispose of resources in the finally block as much as possible
The resources used in the program should be freed to avoid resource leaks. This is best done in the finally block. The finally block is always executed, regardless of the result of the program execution, to ensure that the resource is closed correctly.

16. Try to replace the ' A/b ' operation with a shift
"/" is a costly operation that uses shifting operations to be faster and more efficient
Such as
int num = A/4;
int num = A/8;
should be changed to
int num = a "2;
int num = a "3;
Note, however, that the shift should be annotated because the shift operation is not intuitive and more difficult to understand

17. Try to use shift instead of ' a*b ' operation
Similarly, for the ' * ' operation, using the 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;

18. Try to determine the capacity of the StringBuffer
The StringBuffer constructor creates an array of characters with a default size (usually 16). In use, if this size is exceeded, the memory is redistributed, a larger array is created, the original array is copied, and the old array is discarded. In most cases, you can specify the size when creating the StringBuffer, which avoids auto-growth when the capacity is insufficient to improve performance.
such as: stringbuffer buffer = new StringBuffer (1000);

19. Release references to useless objects as early as possible
Most of the time, the object referenced by the method local reference variable becomes garbage as the method ends, so most of the time the program does not have to explicitly set the local, reference variable to NULL.
For example:
Java code
public void Test () {
Object obj = new Object ();
......
Obj=null;
}
The above is not necessary, and as the execution of the method test () is completed, the scope of the OBJ reference variable in the program ends. But if it's changed to the following:
Java code
public void Test () {
Object obj = new Object ();
......
Obj=null;
Execute time-consuming, memory-intensive operations, or call time-consuming, memory-intensive methods
......
}
At this point it is necessary to assign the OBJ value to null to release the reference to the object as soon as possible.

20. Try to avoid using two-dimensional arrays
Two-dimensional data occupy more memory space than one-dimensional array, about 10 times times more.

21. Try to avoid using split
Unless it is necessary to avoid using split,split because it supports regular expressions, it is less efficient, and if it is frequent dozens of, millions of of calls will be resource intensive, and if you do need to call split frequently, Consider using Apache's Stringutils.split (String,char), which can cache results with frequent split.

ArrayList & LinkedList
One is a linear table, one is a list, a sentence, random query as far as possible to use arraylist,arraylist better than linkedlist,linkedlist also move the pointer, add the deletion of the operation LinkedList better than ArrayList, ArrayList also want to move the data, but this is a theoretical analysis, it is not necessarily the case, it is important to understand the 2 data structure, the right remedy. ArrayList, LinkedList difference: http://blog.csdn.net/ochangwen/article/details/51055722

23. Use System.arraycopy () as much as possible instead of iterating through the array
System.arraycopy () is much faster than copying an array by looping.
24. Try to cache frequently used objects
As much as possible to cache objects that are used frequently, you can use arrays, or hashmap containers for caching, but this can cause the system to consume too much cache and degrade performance, and it is recommended to use some third-party open source tools such as Ehcache,oscache for caching. They basically implement a cache algorithm such as Fifo/flu.

25. Try to avoid very large memory allocations
Sometimes the problem is not caused by the heap state at the time, but by the failure of the allocation. The allocated memory blocks must be contiguous, and as the heap becomes more and more full, it becomes increasingly difficult to find larger contiguous blocks.

26. Caution With exceptions
When creating an exception, you need to collect a stack track, a stack trace that describes where the exception was created. Building these stack traces requires a snapshot of the runtime stack, which is a very expensive part. When you need to create a Exception, the JVM has to say: Don't move, I want to save a snapshot of what you are now, so stop the stack and the stack operation temporarily. Stack traces contain not only one or two elements in the runtime stack, but each element in the stack.
If you create a Exception, you have to pay the price. Fortunately, the overhead of catching exceptions is small, so you can use Try-catch to wrap the core content together. Technically, you can even throw an exception at random without a big cost. It is not a throw operation that incurs a performance penalty-although it is somewhat unusual to throw an exception without pre-creating an exception. The real cost is to create the exception. Fortunately, good programming habits have taught us that you should not throw an exception 3,721 or so. Exceptions are designed for exceptional situations and should be kept in mind when used.

-------------------------------------------------------------------------------------------------------------

(1) Replace the new Boolean () with Boolean.valueof (Boolean B)

The memory footprint of the wrapper class is scary, it is N times the basic type of memory consumption (N>2), and the new object is also consumed by the performance.
Let's look at the JDK implementation for boolean.valueof (Boolean B):
The Boolean class provides two constants:
Java code
public static Final Boolean true = new Boolean (true);
public static Final Boolean false = new Boolean (false);

The internal implementation of valueof (Boolean B) is:
Java code
return (b? True:false);
Therefore, replacing the new Boolean () with Boolean.valueof (Boolean B) can save space and improve performance.

(2) Replace the new Integer () with integer.valueof (int i)
Similar to Boolean, there are many occasions when you use integer encapsulation int in Java development, and the values that are usually represented by int are very small. The instantiation of the integer is optimized in the SUN SDK, and the integer class caches 128 to 127 of the 256 state integers, and if you use integer.valueof (int i), the incoming int range is exactly within this, returning a static instance. This will also greatly reduce the memory footprint if we use integer.valueof instead of the new integer.

(3) Use StringBuffer's Append method instead of "+" to add the string.
This has been said n more than n times, this is not much to say.

(4). Avoid too deep class hierarchies and too deep method calls.
Because both are very memory-intensive (especially the method call is a big consumer of stack space).

(5) A variable is defined and instantiated only when it is used.
This is the easiest mistake for beginners, reasonable use of variables, and only when used to define and instantiate it, can effectively avoid memory space and execution performance of waste, thereby improving the efficiency of the Code.

(6) Avoid declaring the created object in the loop body, even if the object occupies little memory space.
This situation is often encountered in our practical applications, and we are prone to make similar mistakes, such as the following code:
Java code
for (int i = 0; i < 10000; ++i) {
Object obj = new Object ();
System.out.println ("obj=" + obj);
}

The above approach wastes a large amount of memory space. The correct approach is as follows:
Java code
Object obj = null;
for (int i = 0; i < 10000; ++i) {
obj = new Object ();
System.out.println ("obj=" + obj);
}
Using the second method of writing above, only a reference to the object is saved in memory, rather than the code in the first way above produces a large number of object references in memory, wastes a lot of memory space, and increases the load of garbage collection. Therefore, it should be avoided to declare the creation object in the loop body.

(7). If multiple conditions in the If judgment use ' | | ' or ' && ', place the most frequently occurring conditions at the front of the expression.
This trick is often effective in improving the performance of the program, especially if the if judgment is placed inside the loop body, the effect is more obvious.

1.JVM manages two types of memory: heap memory (heap), stack memory (stack), which is used primarily to store objects and variables that the program creates or instantiates at run time. Stack memory is used to store methods that are declared static (static) (or non-static) in program code.

The life cycle of objects in 2.JVM, creation phase, application phase, invisible stage, unreachable stage, collection stage, end stage, release phase

4. The main feature of soft reference is that it has strong reference function. This kind of memory is only recycled when there is not enough memory, so when memory is sufficient, they are usually not recycled. It can be used to realize the cache of some common resources and realize the function of cache.
A = new A ();
softreference sr = new SoftReference (a);
A = null;
if (SR!=null) {
A = Sr.get ();
}else{
A = new A ();
sr = new SoftReference (a);
}

5. The most significant difference between a weak reference object and a soft reference object is that the GC, when it recycles, needs to check whether the soft reference object is reclaimed by the algorithm, and the GC is always recycled for weak reference objects.
A = new A ();
WeakReference wr = new WeakReference (a);
A = null;
if (SR!=null) {
A = Wr.get ();
}else{
A = new A ();
WR = new WeakReference (a); }

6. Shared static variable storage space

7. Sometimes we want to be able to reuse some of the objects that have been created to make use of object pooling in order to improve system performance and avoid repetitive time-consuming operations. Similar to JDBC connection pooling.

8. Instantaneous value, when serializing an object large variable, if this large variable has no purpose, then use transient declaration, do not serialize this variable. At the same time the network transmission is not transmitted.

10. (1) The most basic suggestion is to release the reference of the useless object as soon as possible
A = new A ();
A = null; When you use object A, you actively set it to empty
(2) Use the Finalize function as little as possible.

(3) If you need to use a frequently used picture exhibition, you can use a soft reference.

(4) Pay attention to the collection data types, including arrays, trees and other data, these data structures for GC, recycling is more complex,

(5) Try to avoid creating in the class's default constructor, initialize a large number of objects, and prevent unnecessary memory resource wastage when invoking its own class constructor.

(6) Try to avoid forcing the system to do garbage memory recovery.

(7) Try to avoid explicit application of array space.

(8) Try to use object pooling techniques to improve system performance and reduce the overhead of system memory in the appropriate scenario.

11. As an array copy operation, using the System.arraycopy () method to complete the copy operation is more efficient than using the loop to complete the array copy operation

12. Try to avoid calling methods in the loop body, because method calls are more expensive.

13. Try to avoid using try-catch blocks in the loop body, preferably using try--catch blocks outside the loop body to improve system performance.

14. In multiple loops, if possible, try to put the longest cycle in the most inner layer, the shortest loop on the outermost, to reduce the number of transitions between the cycle layer.

15. In the case of thread safety, use list List = Collections.synchronizedlist (new ArrayList ());

16. If the length is predicted, set the length of the ArrayList.

ArrayList and LinkedList selection, familiar with the underlying principle of implementation, select the appropriate container.

18. String summation using StringBuffer.

19. System I/O optimization, using buffering and compression technology. Optimize performance.

20. Avoid initializing other classes in the class in the constructor

21 try to avoid assigning static variables in the construction

22. Do not create an instance of the class in the class's constructor

23. Combinatorial Optimization Inheritance

24. Preferably through Class.forName () Dynamic loading class

JSP optimization, using the Print method in the Out object instead of the println () method

26. Replace JspWriter object with Servletoutputstream object

27. Initialize the size of the out object buffer with the appropriate values

28. Try to redirect the new JSP using the Forward () method

29. Using thread pooling technology to process customer requests

30.Servlet optimization

(1) Use the init () method to cache some static data to improve application performance.

(2) Replace the println () method with the print () method.

(3) Replace PrintWriter with Servletoutputstream.

(4) Minimize the number of simultaneous code

31. Ways to improve the performance of servlet applications

(1) Do not use Singlethreadmodel

(2) using thread pool ThreadPool

EJB optimization

Entity EJB:

(1) Common data cache and release in entity EJB

(2) loading associated data in a deferred load manner

(3) Apply CMP type entity EJB as much as possible

(4) Direct use of JDBC technology to process large data

33. Optimizing the JDBC Connection

(1) Set the appropriate prefetch row values

(2) Using connection pooling technology

(3) all reasonable application affairs

(4) Select the appropriate transaction isolation layer and close the connection object in time

PREPAREDSTATEMETN only compiles the parse once, and statement compiles the parse every time.

35. Do batch updates as much as you can

36. Improve system performance by using the appropriate GetXXX method

37. Use design mode.

Java Program Optimization Details

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.