The following is a summary of some of the network resources that should be done as much as possible in Java programming.
1. Use the singleton whenever possible
The use of Singleton can reduce the load burden, shorten the loading time, and improve the loading efficiency, but not all of them are applicable to singleton. Simply put, the Singleton is applicable to the following three scenarios:
- Controls the use of resources and controls concurrent resource access through thread synchronization;
- Control the generation of instances to save resources;
- Control data sharing and allow communication between multiple irrelevant processes or threads without establishing a direct association.
2. Avoid using static variables whenever possible
You must know that when an object is referenced by a variable defined as stataic, GC usually does not recycle the memory occupied by this object, such
Public Class A {static B = new B ();} at this time, the lifecycle of static variable B is synchronized with class A. If Class A is not uninstalled, the object B is resident in the memory, until the program ends.
3. Avoid creating too many Java objects.
Try to avoid new objects in the frequently called methods and loops. Because the system not only takes time to create objects, but also takes time to recycle and process these objects, within the scope that we can control, we recommend that you replace objects with basic data types or arrays to maximize the reuse of objects.
4. Try to use the final Modifier
Classes with final modifiers cannot be derived. There are many examples of final applications in the Java core API, such as Java. Lang. String. Specify final for the string class to prevent the user from overwriting the length () method. In addition, if a class is final, all methods of the class are final. The Java compiler will look for opportunities to inline (Inline) All final methods (this is related to the specific compiler implementation ). This can increase the performance by an average of 50%.
5. Use local variables whenever possible
The parameters passed during method calling and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables and instance variables, are created in heap, which is slow.
6. Try to handle the places of use of the packaging type and basic type
Although the packaging types and basic types can be converted to each other during use, the memory areas generated by the two are completely different. The basic types of data are generated and processed in the stack, the packaging type is an object that generates instances in the heap.
The packaging type is applicable to processing objects in collection objects. Other Processing Methods advocate the use of basic types.
7. Use synchronized with caution to minimize synchronize.
We all know that implementing synchronization requires a lot of system overhead as a cost, and may even cause deadlocks, so we should avoid unnecessary synchronization control as much as possible. When the synchronize method is called, the current object is directly locked. Other threads cannot call other methods of the current object until the method is executed. Therefore, the synchronize method should be as small as possible, and the method synchronization should be used instead of the code block synchronization.
8. Use stringbuilder and stringbuffer for string connection whenever possible
I will not talk about this much.
9. Try not to use the Finalize method
In fact, it is very difficult to put the resource cleanup in the Finalize method. Due to the heavy GC workload, especially when the young generation memory is reclaimed, the application will be suspended, therefore, the Finalize method can be used to clean up resources, resulting in a greater GC burden and worse program running efficiency.
10. Try to replace the object with the basic data type
String STR = "hello"; the above method creates a "hello" string, and the JVM character cache pool also caches this string;
String STR = new string ("hello"); in this case, in addition to creating a string, the string object referenced by STR also contains an array of char [] at the bottom, the Char [] array stores H, E, l, l, O in sequence.
11. Use hashmap and arraylist as much as possible for a single thread
Hashtable and vector use synchronization mechanisms to reduce performance.
12. Create a hashmap as reasonably as possible
When you want to create a relatively large hashmap, make full use of the other constructor public hashmap (INT initialcapacity, float loadfactor) to prevent hashmap from performing hash reconstruction multiple times, expansion is a very performance-consuming task. By default, initialcapacity is only 16, while loadfactor is 0.75. You 'd better accurately estimate the size of the required capacity, the same is true for hashtable and vectors.
# P #
13. reduce repeated variable calculation as much as possible
For example
For (INT I = 0; I <list. Size (); I ++) should be changed
For (INT I = 0, Len = List. size (); I <Len; I ++) and avoid using complex expressions in a loop. in a loop, loop conditions are calculated repeatedly. If complex expressions are not used, if the cyclic condition value remains unchanged, the program runs faster.
14. Avoid unnecessary creation as much as possible
For example
A A = new A (); if (I = 1) {list. Add (a);} should be changed
If (I = 1) {A = new A (); list. Add ();}
15. release resources in finally blocks as much as possible
The resources used in the program should be released to avoid resource leakage. This should be done in finally blocks. Regardless of the execution result of the program, the Finally block is always executed to ensure that the resource is properly closed.
16. Use shift as much as possible to replace the operation of 'a/B'
"/" Is a very costly operation. Using shift operations will be faster and more effective.
For example
Int num = A/4; int num = A/8; it should be changed
Int num = A, 2; int num = A, 3; note that notes should be added when using shift, because the shift operation is not intuitive and difficult to understand.
17. Try to use shift instead of 'a * B '.
Similarly, for the '*' operation, the shift operation will be faster and more effective.
For example
Int num = A * 4; int num = A * 8; it should be changed
Int num = A 2; int num = A 3;
18. Determine stringbuffer capacity as much as possible
The stringbuffer constrtor creates a character array of the default size (usually 16. In use, if the size exceeds this value, the memory will be re-allocated, a larger array will be created, the original array will be copied, and then the old array will be discarded. In most cases, you can specify the size when creating the stringbuffer, which avoids automatic growth when the capacity is insufficient to improve performance.
For example:
Stringbuffer buffer = new stringbuffer (1000 );
19. Release reference of useless objects as early as possible
Most of the time, the object referenced by the local reference variable of the method will become junk as the method ends. Therefore, most of the time, the program does not need to set the local reference variable to null explicitly.
For example:
Public void test () {object OBJ = new object ();...... OBJ = NULL;} The above is unnecessary. With the execution of the method test (), the scope of the variable referenced by OBJ in the program ends. But if it is changed to the following:
Public void test () {object OBJ = new object ();...... OBJ = NULL; // the execution time, memory consumption, or calling time and memory consumption methods ...... } In this case, it is necessary to assign the OBJ value to null and release the reference to the object as soon as possible.
20. Avoid using 2D arrays whenever possible
The two-dimensional data occupies much more memory space than the one-dimensional array, which is about 10 times more.
21. Avoid using split whenever possible
Unless necessary, you should avoid using split. Because split supports regular expressions, the efficiency is relatively low. If it is frequently used for dozens of times, millions of calls will consume a lot of resources, if you need to call split frequently, you can consider using Apache's stringutils. split (string, char). Results can be cached for frequent split operations.
22. arraylist & role list
One is a linear table and the other is a linked list. In a single sentence, arraylist should be used for random queries as much as possible. arraylist is better than the sort list, And the sort list also needs to move the pointer. The sort list is better than the arraylist operation, however, this is a theoretical analysis. This is not necessarily the case. It is important to understand the data structure of the two persons and take the right medicine.
23. Try to use system. arraycopy () instead of copying arrays cyclically.
System. arraycopy () is much faster than copying arrays through loops.
24. cache frequently used objects as much as possible
Cache frequently-used objects as much as possible. You can use arrays or hashmap containers to cache objects. However, this method may cause the system to occupy too much cache and degrade performance, we recommend that you use some third-party open-source tools, such as ehcache and Oscache, to cache data. They basically implement caching algorithms such as FIFO and flu.
25. Avoid very large memory allocation whenever possible
Sometimes the problem is not caused by the current heap status, but by allocation failure. The allocated memory blocks must be continuous. As the heap becomes more and more full, it is increasingly difficult to find larger contiguous blocks.
26. Use exceptions with caution
When creating an exception, you need to collect a stack trace that describes where the exception was created. When building these stack traces, you need to create a snapshot for the runtime stack, which is a huge overhead. When an exception needs to be created, the JVM has to say: don't change. I want to save a snapshot as you are, so temporarily stop the inbound and outbound operations. Stack tracing contains not only one or two elements in the runtime stack, but also each element in the stack.
If you create an exception, you have to pay the price. Fortunately, exception capturing does not overhead much, so try-catch can be used to wrap the core content. Technically, you can even throw an exception at will without a high cost. Performance loss is not caused by throw operations (although it is a bit unusual to throw an exception without a pre-created exception ). The real cost is creation exceptions. Fortunately, good programming habits have taught us not to throw exceptions regardless of November. Exceptions are designed for exceptions and should be kept in mind when used.
From: http://hanlincademy.iteye.com/blog/1671914