Measures to reduce GC overhead: The operation of the program will directly affect the system environment changes, thus affecting the GC trigger. Without design and coding for GC features, there is a series of negative effects such as memory presence. To avoid these effects, the basic principle is to minimize the garbage and reduce the cost of the GC process as much as possible. Specific measures include the following:
(1) Do not explicitly call System.GC ()
This function recommends that the JVM perform the main GC, although it is only recommended, but not necessarily, but in many cases it triggers the main GC, increasing the frequency of the main GC, which increases the number of intermittent pauses.
(2) Minimizing the use of temporary objects
Temporary objects will become garbage after jumping out of function calls, and less temporary variables will be equivalent to reducing garbage generation, thus prolonging the occurrence of the second triggering condition mentioned above and reducing the chance of the main GC.
(3) It is best to explicitly set NULL when an object is not used
In general, NULL objects are treated as garbage, so explicitly setting unused objects to NULL is useful for GC collectors to determine garbage, which increases the efficiency of the GC.
(4) Try to use StringBuffer instead of string to accumulate strings (see blog Another article in Java, String and StringBuffer)
Because string is a fixed-length string object, when the string object is accumulated, it is not amplified in a string object, but instead re-creates a new string object, such as STR5=STR1+STR2+STR3+STR4, which produces multiple garbage objects during the execution of the statement. Because a new string object must be created for the "+" operation, these transition objects are meaningless to the system and only add more garbage. Avoid this situation can use StringBuffer to accumulate the string, because the StringBuffer is variable long, it expands on the original basis, does not produce intermediate objects.
(5) can use basic type such as Int,long, do not Integer,long object
A basic type variable consumes much less memory resources than the corresponding object, and it is best to use basic variables if it is not necessary.
(6) Minimize the use of static object variables
Static variables are global variables, are not recycled by GC, and they always consume memory.
(7) time when the object was created or deleted
Concentrating on creating new objects in a short amount of time, especially large objects, can result in a sudden need for a lot of memory, and in this case the JVM can only perform a primary GC to reclaim memory or consolidate memory fragments, thereby increasing the frequency of the main GC. The same is true for deleting objects centrally. It makes a large number of garbage objects suddenly appear, and the free space inevitably decreases, which greatly increases the chance of forcing the main GC the next time the new object is created.
Reduce Java GC