Some suggestions for Java memory optimization and performance optimization

Source: Internet
Author: User
Tags finally block modifier stack trace

1. Do not use static variables if necessary

Developers of Java know that when an object is defined as referenced by the STATAIC variable, the memory that the object occupies will not be recycled. Sometimes, developers define static objects or variables that are often called to improve the performance of the program. Therefore, it is not a common object or variable, not defined as a static type of variable, especially the definition of statically class objects, it must be carefully considered whether it is necessary. For example

    public class x{           static y a = new Y ();       }   

When Class X is created and is not recycled, static variable a always consumes memory.

2. Make full use of the single-case mechanism

Practical single example can reduce the load of resources, shorten the running time and improve the system efficiency. However, the Singleton is not available in all places. In short, a single case can be applied to the following two areas:

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. Reducing the creation of objects

Try to avoid looping through the new objects in frequently invoked methods, as the system takes time not only to create objects, but also to take the time to garbage-collect and process those objects. The enjoy meta pattern in design mode is designed to reduce the number of objects created multiple times. To maximize the reuse of objects within the limits of what we can control, sometimes it is better to replace objects with basic data types or arrays.

4. Using the final modifier

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 arguments passed when the method is called and the temporary variables created in the call are saved in the stack (stack) that is assigned to the method, which is faster. Other variables, such as static variables, instance variables, and so on, are created in the heap and are slower.

6. 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 types of data generation and processing in the stack, while wrapper types are objects that produce instances in the heap. In the collection class object, there is an object aspect required to handle the applicable wrapper type, other cases, it is recommended to promote the use of basic types.

7. Learn to use StringBuilder and StringBuffer
The difference between the two classes is needless to say, the single-threaded use of StringBuilder, multi-threaded use of stringbuffer, so performance will be greatly improved.

7. Try not to use the Finalize method

In fact, it is a very bad choice to put resource cleanup in the Finalize method. Because of the heavy workload of GC, especially when recovering Young's memory, most of them cause the application to pause, so choosing the Finalize method to clean up the resource can cause the GC to be more burdensome and the program will run more efficiently.

8. Try to use basic data types instead of objects

String str = "Hello";

This method creates a "Hello" string, and the JVM's character cache pool 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

I also write a blog about this question, please check out my blog about performance optimization.

9. Learn to use HashMap, ArrayList

HashTable, vector, etc. used in multi-threaded occasions, the internal use of synchronization mechanism, which will reduce the performance of the program.
10. In-depth understanding of hashmap principles

When you want to create a larger hashmap, take advantage of another constructor

Public HashMap (int initialcapacity, float loadfactor) avoids HashMap multiple hash refactoring, which is a very expensive thing to do in the default initialcapacity of only 16, and Loadfactor is 0.75, how much capacity you need, you better be able to accurately estimate the optimal size you need, the same hashtable,vectors is the same truth.

11. Reduce the repeated calculation of variables

Such as

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

Should be rewritten as:

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

Or

for (int i = list.size (); I >-1; i--)

And in the loop should avoid the use of complex expressions, in the loop, the loop condition will be repeated calculation, if you do not use complex expressions, and the loop condition value is not changed, the program will run faster.

12. Avoid unnecessary creation of objects

Such as

A = new A ();

if (i==1) {list.add (a);}

should read

if (i==1) {

A = new A ();

List.add (a);}

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

14. Use shift instead of multiplication or division (' A/b ', only for 2^n cases)

"/" 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

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 be changed to

int num = a << 2;

int num = a << 3;

15. 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: Stringbufferbuffer = new StringBuffer (1000);

16. 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:

public void Dojob () {

Object obj =new object ();

......

Obj=null;

}

The above is not necessary, as the execution of the method Dojob () completes, the scope of the OBJ reference variable in the program is collected by GC. But if it's changed to the following:

public void Dojob () {

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.

17. Try to avoid using split

Unless it is necessary to avoid using split,split because of the support of regular expressions, so the efficiency is low, if it is frequent dozens of, millions of of the call will be a lot of resources, if you do need to call split frequently, you can consider using Apache's Stringutils.split (String,char), frequent split can cache results.

18.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 to move the data, but this is a theoretical analysis, it is not necessarily the case, it is important to understand the good data structure.

19. Use System.arraycopy () as much as possible instead of iterating through the array

System.arraycopy () is much faster than copying an array by looping

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

21. 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 heap heap becomes more and more full, it becomes increasingly difficult to find larger contiguous blocks.

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

Some suggestions for Java memory optimization and performance optimization

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.