Java program performance optimization skills and java performance optimization skills
1. Optimize the loop body
If the number of loops is large, the problems with poor code processing in the loop body will be magnified.
For (int I = 0; I <list. size (); I ++) {} is optimized to int size = list. size (); for (int I = 0; I <size; I ++) {}for (int I = 0; I <100000; I ++) {if (I % 10 = 9) {// execute 10 times per loop} is optimized to for (int I = 0; j = 10; I <100000; I ++; j --) {if (j = 0) {// execute j = 10 every 10 times ;}}
2. Use new to initialize an instance.
The time consumed by a new object is often thousands of times the time consumed by the assignment of a local variable. At the same time, the system also needs to spend time garbage collection and processing after the object is generated.
For example:
NewObject object = new NewObject ();
Int value;
If (value> 10 ){
Value = object. getValue ();
}
Optimized
Int value;
If (value> 10 ){
NewObject object = new NewObject ();
Value = object. getValue ();
}
3. Exception Handling
Exception Handling is detrimental to performance. When an exception is thrown, you must first create a new object and perform related processing, resulting in system overhead. Therefore, exceptions should be used to handle errors and should not be used to control program processes.
4. Use local variables whenever possible
Local variables, parameters passed during method call, and temporary variables created are saved in the stack, which is fast. Other variables are added to static variables and global variables in Heap) the creation speed is slow.
Extended: the stack is allocated by the system, and the speed is fast. The stack uses a level-1 cache, which is usually in the storage space when called, and is released immediately after the call is completed, heap is the memory allocated by the new system, which is prone to memory fragmentation. However, it is easy to use. The heap is stored in the second-level cache, and its lifecycle is determined by the garbage collection algorithm of the virtual machine.
5. Minimize I/O operations
6. Use cache whenever possible
BufferedReader replaces Reader, BufferedWriter replaces Writer, and BufferedInputStream replaces inputStream for I/O processing, which improves performance.
7. Try not to use synchronization. Servlet is a multi-thread. If too many syncs are used, the advantage of Multithreading is lost.
8. Too much information cannot be stored in HttpSession, but the memory needs to be high when the session storage volume is large.
9. eliminates the session and manually releases resources when the user exits the system.