Avoid creating objects in the loop body

Source: Internet
Author: User
Tags data structures finally block garbage collection modifier stack trace wrapper stringbuffer

Here are some of the things you can do in Java programming that refer to the summary of your network resources.

1. Try to use a single case on the right occasion

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 the single case, in simple terms, single cases are mainly used in the following three aspects:

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

Second, the control instance is produced to achieve the goal of saving resources;

Third, the control of data sharing, without establishing a direct correlation, so that a number of unrelated processes or threads to achieve communication between.

2. Avoid arbitrary use of static variables as far as possible

You know, when an object is defined as a reference to a STATAIC variable, the GC usually does not reclaim the memory that the object occupies, such as

Java code

public class a{

Static B = new B ();

}

At this point, the life cycle of static variable B is synchronized with Class A, and if Class A does not unload, then the B object will reside in memory until the program terminates.

3. Try to avoid creating Java objects too often

Try to avoid the methods that are frequently invoked, the new object in the loop, because the system not only takes time to create objects, but also takes time to garbage collection and processing of these objects, in the range we can control to maximize the reuse of objects, preferably with a basic data type or array to replace the object.

4. Use final modifier as far as possible

A class with the final modifier is not derived. In the Java Core API, there are many examples of final application, such as java.lang.String. Specifying final for the String class prevents the user 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 to inline (inline) all final methods (this is related to the specific compiler implementation). This will increase performance by an average of 50%.

5. Use local variables as much as possible

The parameters passed when the method is invoked and the temporary variables created in the call are saved in the stack (stack) faster. Other variables, such as static variables, instance variables, and so on, are created in the heap (Heap) in a slower speed.

6. To deal with the type of packaging and basic types of the use of the site

Although the wrapper type and base type can be converted to each other during use, the memory areas produced by both are completely different, the base type data generation and processing are processed on the stack, the wrapper type is an object, and an instance is generated in the heap.

In the collection class object, there is an object aspect needed to handle the application of the wrapper type, and other processing advocates the use of the base type.

7. Careful use of synchronized, to minimize the Synchronize method

All know, to achieve synchronization is a very large system overhead as a cost, and may even cause deadlock, so try to avoid unnecessary synchronization control. When the Synchronize method is invoked, the current object is locked directly, and other threads cannot invoke other methods of the current object until the method has been executed. So the Synchronize method is as small as possible, and should try to use method synchronization instead of code block synchronization.

8. Use StringBuilder and StringBuffer for string connection as far as possible

I don't have much to say about that.

9. Try not to use the Finalize method

In fact, it's a bad choice to put resource cleanup in the Finalize method, because the GC is a lot of work, especially when it comes to recovering the memory of young generations, which causes the application to pause, so choosing to use the Finalize method for resource cleanup can result in a greater GC burden. Programs run less efficiently.

10. Use basic data types as much as possible instead of objects

String str = "Hello";

The above method creates a "Hello" string, and the JVM's character cache pool caches the string;

String str = new string ("Hello");

At this point, in addition to creating a string, the string object referenced by Str contains a char[] array, which in turn stores the char[array h,e,l,l,o

11. Single thread should try to use HashMap, ArrayList

HashTable, vector and so on use the synchronization mechanism, reduces the performance.

12. Create HashMap as reasonable as possible

When you want to create a larger hashmap, make the most of another constructor

Public HashMap (int initialcapacity, float loadfactor)

Avoid HashMap multiple hash refactoring, expansion is a very performance-consuming thing, in the default of Initialcapacity only 16, and Loadfactor is 0.75, how much capacity you need to accurately estimate the best size you need, The same hashtable,vectors is the same.

13. To minimize the duplication of the calculation of variables

Such as

for (int i=0;i

should read

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

And in the loop should avoid the use of complex expressions, in the loop, the loop condition will be repeatedly computed, if not the use of complex expressions, and the loop condition value unchanged, the program will run faster.

14. Try to avoid unnecessary creation

Such as

A A = new A ();

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

should read

if (i==1) {

A A = new A ();

List.add (a);}

15. Try to release resources in finally blocks

The resources used in the program should be freed to avoid resource leaks. It's better to do it in the finally block. The finally block is always executed, regardless of the outcome of the program execution, to ensure that the resource is properly closed.

16. Use shift instead of ' A/b ' operation as far as possible

"/" is a costly 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;

Note, however, that the use of shifts should be annotated, because the shift operation is not intuitive, more difficult to understand

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

Similarly, for ' * ' operations, using shift operations 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 StringBuffer

The StringBuffer constructor creates a character array of the default size (usually 16). In use, if this size is exceeded, the memory is reassigned, 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 stringbuffer, thus avoiding automatic growth when there is not enough capacity to improve performance.

such as: stringbuffer buffer = new StringBuffer (1000);

19. Release the references to the unwanted 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 need to explicitly set the local, reference variable to NULL.

For example:

Java code

public void Test () {

Object obj = new Object ();

......

Obj=null;

}

This is not necessary, and as the execution of the method test () completes, 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;

Perform time-consuming, memory-intensive operations, or invoke time-consuming, memory-consuming methods

......

}

It is necessary at this point to assign obj to null and to release the reference to object objects as soon as possible.

20. Try to avoid using two-dimensional arrays

Two-dimensional data occupies much more memory space than a one-dimensional array, about 10 times times more.

21. Try to avoid using split

Unless it is necessary, you should avoid the use of split,split because of the support of regular expressions, so inefficient, if the frequent dozens of, millions of of the call will consume a lot of resources, if you do need frequent call split, You can consider using Apache Stringutils.split (String,char), which can cache results with frequent split.

ArrayList & LinkedList

One is a linear table, one is linked list, in a word, random query as far as possible to use arraylist,arraylist better than linkedlist,linkedlist also move the pointer, add delete operation LinkedList better than ArrayList, ArrayList also want to move data, but this is theoretical analysis, the fact is not necessarily so, it is important to understand 2 of the data structure, the right remedy.

23. Try to use System.arraycopy () instead of iterating through the array

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

24. Cache frequently used objects as much as possible

Caching frequently used objects as much as possible, using arrays, or hashmap containers, may cause the system to consume too much cache and degrade performance, and it is recommended that you use some third-party open-source tools such as Ehcache,oscache for caching. They have basically realized the fifo/flu and so on cache algorithm.

25. Try to avoid very large memory allocations

Sometimes the problem is not caused by the state of the heap at the time, but by the allocation failure. 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. Use exceptions with caution

When an exception is created, a stack trace (stack track) is gathered to describe where the exception was created. Building these stack traces requires a snapshot of the runtime stack, and that's a huge part of the overhead. 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 like, so temporarily stop the stack and the stack operation." The stack trace contains not only one or two elements in the runtime stack, but each element of the stack.

If you create a Exception, you have to pay the price. Fortunately, the catch exception is not expensive, so you can use Try-catch to wrap up the core content. Technically, you can even throw an exception at random without paying a great price. Performance loss is not a throw operation-although it is unusual to throw an exception without creating an exception in advance. The real cost is to create an exception. Fortunately, good programming habits have taught us that we should not throw exceptions regardless of 3,721. 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 very scary, it is the basic type of memory occupied by N Times (N>2), while the new object is also a performance consumption.

Let's look at the JDK's 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);

Thus substituting boolean.valueof (Boolean B) for new Boolean () can save space and improve performance.

(2). Replace the new Integer () with integer.valueof (int i)

As with Boolean, there are also many occasions in Java development that use integer encapsulation int, and the values usually expressed in int are very small. The integer instantiation is optimized in the SUN SDK, the integer class caches 128 to 127 of these 256 states, and if you use integer.valueof (int i), the incoming int range is right here, returning the static instance. This will also greatly reduce memory consumption if we use integer.valueof instead of the new integer.

(3). Use the StringBuffer Append method instead of "+" to add strings.

This has been the n many people said N times, this is not much to say.

(4). Avoid too-deep class hierarchies and too-deep method calls.

Because both of these are very memory-intensive (especially the method invocation is a large consumer of stack space).

(5). A variable is defined and instantiated only when it is used.

This is the easiest for beginners to make mistakes, rational use of variables, and only when it is used to define and instantiate, can effectively avoid the memory space and performance of the waste, so as to improve the efficiency of the Code.

(6). Avoid declaring the creation object in the loop body, even if the object occupies little memory space.

This situation is often encountered in our practical applications, and we can easily 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 above, only a reference to the object is saved in memory, rather than the code in the first way above, which produces a lot of object references in memory, wastes a lot of memory and increases the load of garbage collection. So declaring the creation object in the loop body should be avoided as much as possible.

(7). If there are multiple conditions in the If judgment with ' | | ' or ' && ', put the most frequently occurring condition at the top of the expression.

This technique is often effective in improving the performance of the program, especially when the if judgment is placed inside the loop body.

1.JVM manages two types of memory: heap memory (heap), stack memory (stack), and the underlying heap is primarily used 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, the creation phase, the application phase, the invisible stage, the unreachable stage, the collection stage, the end stage, the release stage of the object in 2.JVM

3. Avoid creating objects in the loop body, even if the object has little memory space.

for (int i=0;i<10000;++i) {

Object obj = new Object ();

System.out.println ("obj=" +obj);

}

should be changed into

Object obj = null;

for (int i=0;i<10000;++i) {

obj = new Object ();

System.out.println ("obj=" +obj);

}

4. The main feature of soft reference is that it has strong reference function. This type of memory is recycled only when there is not enough memory, so they are usually not recycled when memory is sufficient. It can be used to realize the cache of some common resources and realize the function of cache.

A 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 important difference between a weak reference object and a soft reference object is that the GC, in the case of a recycle, needs an algorithm to check whether to recycle the soft reference object, while the GC always reclaims the weak reference object.

A 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 in order to improve the performance of the system, to avoid repeated time-consuming operations, we hope to be able to reuse some of the creation of completed objects, using object pool implementation. Similar to a JDBC connection pool.

8. Instantaneous value, when serializing an object large variable, if the large variable is not useful, use the transient declaration to not serialize the variable. It is also not transmitted in the network transmission.

9. Do not create objects in advance

void F () {

int i;

A A = new A ();

if (...) {

A.showmessage ();

}

}

Change into

void F () {

int i;

A A = null;

if (...) {

Instantiated only when used

A = new A ();

A.showmessage ();

}

}

10. (1) The most basic advice is to release the references of unwanted objects as soon as possible

A A = new A ();

A = null; Actively set it to null when object A is used

(2) Use the Finalize function as little as possible.

(3) Use a soft reference if you need to use a photo show that you use frequently.

(4) Attention to collection data types, including arrays, trees and other data, these data structures for GC, recovery more complex,

(5) Try to avoid creating in the default constructor of the class, initializing a large number of objects, and preventing unnecessary waste of memory resources when invoking the constructor of its own class.

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

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

(8) Use object pooling technology to improve system performance and reduce system memory overhead as far as possible in appropriate scenarios.

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

12. Try to avoid calling methods in the body of the loop 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 to improve system performance.

14. In multiple loops, if possible, try to put the longest loop in the outermost layer, the shortest loop at the outer layer, to reduce the number of transformations between the loop layers.

15. Use the list List = Collections.synchronizedlist (new ArrayList ()) In cases where thread safety is required;

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

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

18. String additive uses StringBuffer.

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

20. Avoid other classes in class initialization in constructors

21 as far as possible to avoid in the construction of static variables to do assignment operations

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

23. Combinatorial Optimization Inheritance

24. Preferably through the 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 value

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

29. Process customer requests using thread pooling technology

30.Servlet optimization

(1) The Init () method is used to cache some static data to improve the application performance.

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

(3) Replace PrintWriter with Servletoutputstream.

(4) Try to reduce the number of synchronized code

31. Ways to improve servlet application performance

(1) Do not use Singlethreadmodel

(2) using the thread pool ThreadPool

EJB optimization

Entity EJB:

(1) Common data caching and release in entity EJB

(2) loading associated data in a deferred loading manner

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

(4) Directly using JDBC technology to deal with large data

33. Optimizing JDBC Connections

(1) Set the appropriate prefetch line value

(2) Using Connection pool 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 parsing every time.

35. Do the batch update as much as possible

36. Improve system performance by adopting appropriate GetXXX method

37. Adopt design pattern.


Original source from "Bit net", reprint please keep the original link: http://soft.chinabyte.com/database/436/12391936.shtml

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.