Comment on the Java coding method circulating on the Internet to improve performance

Source: Internet
Author: User
Tags finally block

Below are some of the practices circulating on the Internet to improve performance. I have made some comments on some of them:

 

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:
First, control resource usage and control concurrent resource access through thread synchronization;
Second, control the generation of instances to save resources;
Third, control data sharing and allow communication between multiple irrelevant processes or threads without establishing a direct association.
[Supported]
2. Avoid using static variables whenever possible
 
You know, when an object is defined as referenced by the stataic variable, GC usually does not recycle the memory occupied by this object, such
 
JavaCode
Public Class {

Static B = new B ();

}

Public Class A {
static B = new B ();
}at this time, the lifecycle of static variable B is synchronized with that of Class, if Class A is not uninstalled, the object B is resident in the memory until the Program is terminated.
[supported]
3. avoid creating too many Java objects as often as possible
avoid calling methods frequently and adding new objects in a loop. Because the system not only takes time to create objects, it also takes time to recycle and process these objects. To maximize the reuse of objects within our control, it is best to replace objects with basic data types or arrays.
[supported]
4. if possible, use the final modifier
class with
final modifier. There are many examples of final applications in the Java core API, such as Java. Lang. String. Set 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 looks 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%.

[highly supported]
5. use local variables as much as possible
parameters passed during method calling and 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.
[This statement is incorrect. It is true only when the local variable is of the original type. If it is an object, it is incorrect .]
6. try to handle the use of the packaging type and basic type
although the packaging type and basic type can be converted to each other during use, however, the memory areas produced by the two are completely different. The basic types of data are generated and processed in the stack. The packaging type is an object and an instance is generated in the heap.
the packaging type is applicable to the processing of collection objects and objects. Other Processing Methods advocate the use of basic types.
[supported]
7. use synchronized with caution and minimize synchronize methods.
all
we know that implementing synchronization requires a large amount of system overhead, which may even cause deadlocks, so try to avoid unnecessary synchronization control. 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.
[supported. Do not use synchronized unless necessary.]
8. try to use stringbuilder and stringbuffer for string connection
This is not much to be said.
[supported]
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 workload of GC, especially when the young generation memory is recycled, the application is suspended. Therefore, the Finalize method can be used to clean up resources, resulting in a greater GC burden and worse program running efficiency.

[Supported]
10. Try to replace the object with the basic data type
 
String STR = "hello ";
In this method, a "hello" string is created, and the JVM character cache pool also caches this string;[In the constant pool]
String STR = new string ("hello ");
In this case, in addition to creating strings, the string object referenced by STR also contains an array of char [] at the bottom layer. The array of char [] Stores H, E, l, l, O in sequence.[This is an incorrect statement. This statement generates two string objects, "hello" in the constant pool and the new object in the heap, however, the new object uses char [], which is the char [] in the constant pool. That is, two string objects share an underlying array.]

[Supported]
11. Use hashmap and arraylist as much as possible for a single thread
Hashtable and vector use synchronization mechanisms to reduce performance.

[Supported]
12. Create a hashmap as reasonably as possible
 
When you want to create a large hashmap, make full use of another constructor.
Public hashmap (INT initialcapacity, float loadfactor)
Dodge
Without hashmap, hash reconstruction is performed multiple times. Resizing is a performance-consuming task. By default, initialcapacity is only 16, while loadfactor is
0.75. How much capacity is required? You 'd better accurately estimate the optimal size you need. The same is true for hashtable and vectors.

[Supported]
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 ++)
In addition, you should avoid using complex expressions in a loop. in a loop, loop conditions are calculated repeatedly. If you do not use a complex expression and keep the value of the loop condition unchanged, the program will run faster.

[Supported]
14. Avoid unnecessary creation as much as possible
 
For example
A A = new ();
If (I = 1) {list. Add ();}
Should be changed
If (I = 1 ){
A A = new ();
List. Add ();}

[Supported]
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.

[Supported]
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;
Should be changed
Int num = A> 2;
Int num = A> 3;
Note that annotations should be added when shift is used, because the shift operation is not intuitive and difficult to understand.

[Objection]
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;
Should be changed
Int num = A <2;
Int num = A <3;

[Objection]
18. Determine stringbuffer capacity as much as possible
 
Stringbuffer

The constructor will create a default size (usually 16) character array. In use, if the size exceeds this value, the memory will be re-allocated, a larger array will be created, and the original array will be copied, and then
Discard the old array. 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 );

[Supported]
19. Release reference of useless objects as early as possible
 
In most cases, objects referenced by partial reference variables of a method become junk as the method ends. Therefore, most of the time, the program does not need to explicitly set the reference variable to null.
For example:
 
Java code
Public void test (){

Object OBJ = new object ();

......

OBJ = NULL;

}

Public void test (){
Object OBJ = new object ();
......
OBJ = NULL;
} This 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:
 
Java code
Public void test (){

Object OBJ = new object ();

......

OBJ = NULL;

// Execution time-consuming, memory-consuming, or calling time-consuming, memory-consuming Methods

......

}

Public void test (){
Object OBJ = new object ();
......
OBJ = NULL;
// Execution time-consuming, memory-consuming, or calling time-consuming, memory-consuming 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.

[Supported]
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.

[Error. Multi-dimensional arrays are arrays without special storage space .]
21. Avoid using split whenever possible
 
Division
It is not necessary. Otherwise, we 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 do need
To frequently call split, you can consider using stringutils. Split (string, char) of Apache. Frequently split can cache results.

 
22. arraylist & role list
 
I
A linear table and a linked list. In a single sentence, arraylist should be used for random queries as much as possible. arraylist is better than the sorted list, and the sorted list must be moved
The number of rows to be deleted is better than that of the arraylist operation. The arraylist operation also needs to move data. However, this is a theoretical analysis. This is not the case, but it is important to understand 2.
The data structure is the right remedy.

[Supported]
23. Try to use system. arraycopy () instead of copying arrays cyclically.
System. arraycopy () is much faster than copying arrays through loops.

[Highly supported]
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 FIFO/Flu caching.Algorithm.

 
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 (stack
track), which 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 you need to create a
exception, JVM
has to say: do not change. I want to save a snapshot as it is, so the inbound and outbound operations are temporarily stopped. 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, the exception capture overhead is not large, so try-catch
can be used to pack 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 little unusual to throw an exception without a pre-created exception. The real cost is creation exceptions. Fortunately, good programming habits have taught us that we should not throw an exception regardless. Exceptions are designed for exceptions and should be kept in mind when used.

Related Article

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.