In addition to the new machine memory, should also be a good review of our code, a lot of code to write too casually, these bad habits or the language of the program is not understood to be a good suppression of repression.
Here are some of the things you can do in Java programming as a summary of the reference network resources.
1. Try to use a single case in the appropriate situationUsing 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: first, control the use of resources, through thread synchronization to control the concurrent access of resources; In order to achieve the purpose of saving resources; Thirdly, control data sharing and enable communication between multiple unrelated processes or threads without establishing a direct association.
2. Try to avoid using static variables arbitrarilyYou know, when an object is defined as being referenced by a STATAIC variable, the GC typically does not reclaim the memory that the object occupies, such 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 objectsTry 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 possibleA 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 possibleThe 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 typeAlthough 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 methodAll 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.
Note:The use of the synchronized keyword does not always lock the current object, but depends on what the specific lock is. If the synchronized is added to the method, it is locked with the object itself, and if it is a static method, the force of the lock is the class.
8. Use StringBuilder and StringBuffer for string connections whenever possibleThat's not much to say.
9. Try not to use the Finalize methodIn 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.Note:The fundamental reason for not recommending a Finalize method is that the JVM's specification does not guarantee when the method is executed, so it is inappropriate to use this method to release resources, potentially causing long-time resources to be freed
10. Try to use basic data types instead of objectsstring str = "Hello"; this method creates a "Hello" string, and the JVM's character cache pool caches the string, and string str = new string ("Hello"), in addition to creating a string, the program The string object referenced by Str also contains a char[] array, and the char[] array is stored in turn h,e,l,l,o
11. Single thread should try to use HashMap, ArrayListHashTable, vectors, etc. use the synchronization mechanism to reduce the performance.
12. Create HashMap as reasonable as possibleWhen you want to create a larger HashMap, take advantage of another constructor public HashMap (int initialcapacity, float loadfactor) to avoid HashMap multiple hash refactoring, Expansion is a very expensive thing, in the default initialcapacity only 16, and Loadfactor is 0.75, how much capacity, you'd better be able to accurately estimate the best size you need, the same hashtable,vectors is the same truth.
13. Minimize the repeated calculation of variablessuch as for (int i=0;i<list.size (); i++) should be changed to for (int i=0,len=list.size (); i<len;i++) and should avoid using complex expressions in loops, The loop condition is calculated repeatedly, and the program will run faster if the loop condition value is not changed without the use of complex expressions.
14. Try to avoid unnecessary creationsuch as a A = new A (); if (i==1) {list.add (a);} Should be changed to if (I==1) {A A = new A (); List.add (a);}
15. Dispose of resources in the finally block as much as possibleThe 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 the shift operation will be faster and more efficient as int num = A/4;int num = A/8; should be changed to int num = a >> 2;int num = a >> 3; Note that the use of shifts should be Add comments, because the shift operation is not intuitive, more difficult to understand
17. Try to use shift instead of ' a*b ' OperationSimilarly, for the ' * ' operation, using the shift operation will be faster and more efficient as int num = a * 4;int num = a * 8; should be changed to int num = a << 2;int num = a << 3;Note:16, 17, the individual does not quite agree with these two articles. This does have better performance, but at the expense of readability. These two operators are not intuitive to many programmers. I think it's a good choice to sacrifice some performance for better readability and maintainability in a situation where hardware prices are not so expensive today.
18. Try to determine the capacity of the StringBufferThe 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 possibleMost 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. 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 arraysTwo-dimensional data occupy more memory space than one-dimensional array, about 10 times times more.
21. Try to avoid using splitUnless 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 & LinkedListOne 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.
23. Use System.arraycopy () as much as possible instead of iterating through the arraySystem.arraycopy () is much faster than copying an array by looping
24. Try to cache frequently used objectsAs 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 allocationsSometimes 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 ExceptionsWhen 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.
Java programming "improve performance" should try to do