The following is a summary of some of the reference network resources Java programming is done in some places as much as possible.
1. Try to use a single example in the appropriate situation
Using a single example can reduce the load burden and shorten the load time. Increase load efficiency, but not all places are suitable for one case. Simply put, the single is mainly applicable to the following three aspects:
First. Control the use of resources, through thread synchronization to control the concurrent access to resources;
Second. Control the generation of instances to achieve the purpose of saving resources;
Third, control data sharing and allow multiple unrelated processes or threads to communicate without establishing a direct association.
2. Try to avoid any use of static variables to know. When an object is defined as referenced by the STATAIC variable, the GC generally does not reclaim the memory that the object occupies, as
public class a{
Static b b = new B ();
}
At this point, the life cycle of static variable B is synchronized with Class A, assuming that class A does not unload, then the B object will reside in memory. Until the program terminates.
3. Try to avoid too often creating Java objects
Try to avoid loops of new objects in frequently called methods, because the system takes time not only to create objects, but also to take time to garbage-collect and process those objects. Within the limits of what we can control. To maximize the reuse of objects, it is best to replace them with major data types or arrays.
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. Also, assuming that a class is final, all methods of the class are final. The Java compiler looks for the opportunity Inline (inline) for all final methods (this is related to the detailed compiler implementation).
This will increase the performance by an average of 50%.
5. Use local variables as much as possible
The parameters that are passed when the method is called and the temporary variables created in the call are saved in the stack. Faster. Other variables, such as static variables, instance variables, and so on. Are created in the heap and are slow.
6. Try to handle the use of both the packing type and the basic type
Although the packing type and the base type can be converted to each other during use. However, the memory areas they produce are completely different, and basic types of data generation and processing are handled in the stack. The wrapper type is an object that is the instance that is generated in the heap.
In the collection class object. There are objects that need to be handled to suit the type of packaging. Other processing advocates the use of basic types.
7. Use synchronized with caution. Try to reduce the Synchronize method
All know that the implementation of synchronization is very large overhead as a cost, and may even cause a deadlock, so try to avoid unnecessary synchronization control.
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 finished running. So the method of synchronize is as small as possible. And you should try to use synchronization instead of code block synchronization.
8. Use StringBuilder and StringBuffer for string connections whenever possible
That's not much to say.
9. Try not to use the Finalize method
In fact, it is a bad choice to put resource cleanup in the Finalize method, because the GC is very heavy, especially when recovering Young's memory. Most will cause the application to pause. So then choose to use the Finalize method for resource cleanup. Can cause the GC to be more burdensome and program execution less efficient.
10. Try to replace the object with the basic data type
String str = "Hello";
In this way, a "hello" string is created. 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 includes 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 a synchronization mechanism to reduce performance.
12. Create HashMap as reasonable as possible
When you want to create a larger hashMap. Make the most of it. There is also a constructor
Public HashMap (int initialcapacity, float loadfactor)
Avoid HashMap multiple hash refactoring, the expansion is a very cost-performance thing, in the default of Initialcapacity only 16. And Loadfactor is 0.75, how much capacity you need, you'd better be able to predict exactly the best size you need. The same hashtable,vectors is the same truth.
13. Minimize the repeated calculation of variables
Such as
for (int i=0;i<list.size (); i++)
should read
for (int i=0,len=list.size (); i<len;i++)
And in the loop, you should avoid using complex expressions, in which the loop condition is repeated. Assume that a complex expression is not used, and that the loop condition value is not changed. The program will execute faster.
14. Try to avoid unnecessary creation of
A = new A ();
if (i==1) {list.add (a);}
should read
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. Regardless of the result of the program running. The finally block will always run. To ensure that resources are properly closed.
16. Use shift to replace ' A/b ' operation "/" is a very expensive operation, the use of 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 note that the use of shift should be added to the gaze, because the shift operation is not intuitive, more difficult to understand
17. Use shift to replace ' a*b ' operation the same, for ' * ' operation, use shift operation will be faster and more effective
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 (typically 16). In use, assuming that this size is exceeded, the memory is allocated again, 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 the ability to actively grow 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 need to be local. The reference variable is explicitly set to NULL.
Like what:
public void Test () {
Object obj = new Object ();
......
Obj=null;
}
The above is not required, and as the method Test () is finished, the scope of the OBJ reference variable in the program ends. But the assumption is to change to the following:
public void Test () {
Object obj = new Object ();
......
Obj=null;
Run time-consuming, memory-intensive, or call time-consuming. How to consume memory
......
}
At this point it may be necessary to assign the OBJ value to null (it should be considered that the JVM has been running for some time.) Obj=null may be deleted.
JIT compilation is the primary way for a virtual machine to run code, and null values are completely eliminated after JIT compilation optimization. The ability to release references to object objects as early 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 required. Otherwise, the use of split,split should be avoided because it supports the normal form, so the efficiency is relatively low, assuming that the frequency is dozens of. A millions of call would be resource intensive, assuming that you do need to call split frequently, and consider using Apache's Stringutils.split (String,char), which can cache results frequently.
ArrayList & LinkedList One is a linear table, one is a linked list, in a word, random queries use ArrayList as much as possible. ArrayList is better than LinkedList. LinkedList also want to move the pointer, add delete operation LinkedList better than Arraylist,arraylist also to move the data, but this is theoretical analysis, the fact is not necessarily so, it is important to understand the data structure of 2, 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. Try to cache frequently used objects
Whenever possible, cache the objects that are used frequently. The ability to use arrays, or hashmap containers, for caching. However, such a way could cause the system to consume too much cache. Performance degradation, it is recommended to use some third-party open source tools. such as Ehcache,oscache cache, they basically implement the fifo/flu and other caching algorithms.
25. Try to avoid a large memory allocation
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. This stack trace is used to describe where the description of the exception was created. Building these stack traces requires a snapshot of the execution time stack, which is a very expensive part. When you need to create a Exception. The JVM had 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." The stack trace includes not only one or two elements in the execution-time stack, but each element in the stack.
Suppose you create a Exception. will 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 arbitrarily without paying a very high price. 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, it is. Good programming habits have taught us that you should not throw an exception no matter 3,721.
exception, and design. It should also be remembered when using this principle.
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Adding Java has several good habits