1. Try to use singletons when appropriate
Using singletons can reduce the load burden, shorten the load time, and improve the load efficiency. However, it is not applicable to all places. Simply speaking, singletons are mainly applicable to the following three aspects:
- Control the use of resources, through thread synchronization to control the concurrent access of resources;
- Control the generation of instances to achieve the purpose of saving resources;
- Control data sharing to allow multiple unrelated processes or threads to communicate without establishing a direct correlation.
2. Avoid arbitrary use of static variables
Remember that when an object is defined as a static variable, the GC usually does not reclaim the memory occupied by the object, as in:
At this point, the lifetime of the static variable B is synchronized with that of class A. If class A is not unloaded, the b object is resident in memory until the program terminates.
3. Avoid creating Java objects too often
Try to avoid in the method called often, cycle of the new object, because the system not only takes time to create the object, but also to spend time to garbage collection and processing of these objects, in we can control the range, maximum reuse objects, best can use object or array to replace basic data type.
4. Use final modifiers whenever possible
Classes with the final modifier are not derivable. In the JAVA core API, there are many examples of using final, such as java.lang.String, where specifying final for the String class prevents the consumer from overwriting the Length method. In addition, if a class is final, all the methods of that class are final. The Java compiler looks for opportunities to inline all final methods (depending on the specific compiler implementation). This can improve performance by an average of 50%.
For example, change getters/setters that access variables in an instance to “final:”
Simple getter/setter methods should be made final. This tells the compiler that the method is not loaded so it can be changed to “inlined”. Example:
5. Use local variables whenever possible
The parameters passed when a method is called, as well as the temporary variables created during the call, are stored in the Stack, which is faster. Other variables, such as static variables, instance variables, etc., are created in the Heap and are slower.
6. Try to deal with the use of both the packaging type and the basic type
Although wrapper types and primitive types are interchangeable in use, the memory areas they generate are completely different. Primitive types are generated and processed in the stack, while wrapper types are objects and instances are generated in the heap. In the case of collection-class objects, processing that has object aspects needs applies to wrapper types, while other processing advocates primitive types.
Use synchronized sparingly, minimizing the use of synchronize
It is well known that synchronization is expensive and can even cause deadlocks, so try to avoid unnecessary synchronization control. When the synchronize method is called, it locks the current object so that no other thread can call any other methods on the current object until the method completes execution. Keep the synchronize method to a minimum and use method synchronization instead of code block synchronization whenever possible.
8. Try not to use finalize methods
As a matter of fact, it is not a good choice to finalize the resource cleaning in Finalize method. Because of the heavy workload of GC, especially when the Young generation memory is recycled, the application program will be paused. Therefore, to finalize the resource cleaning in Finalize method will lead to a heavier burden of GC and a worse running efficiency of the program.
9. Use primitive data types instead of objects whenever possible
String str = “hello”;
Copy the code
This creates a “hello” string, which is cached by the JVM’s character cache pool;
String STR = new String(" hello ");Copy the code
In addition to creating a String, the String referenced by STR also contains a char array containing h, E, L, L, and O
10. Multithreading should use HashMap and ArrayList as far as possible without thread safety
HashTable, Vector, and so on use synchronization, which degrades performance.
11. Create a HashMap as reasonably as possible
Make full use of this constructor when creating a large hashMap
By default, initialCapacity is only 16, and loadFactor is 0.75. You’d better be able to accurately estimate the optimal size you need. Vectors do the same thing.
12. Minimize double counting of variables
Should, should, should
And avoid using complex expressions in loops, where loop conditions are evaluated repeatedly. If you leave the loop condition values unchanged without using complex expressions, the program will run faster.
13. Try to free resources in finally blocks
Resources used in the program should be released to avoid resource leakage. This is best done ina finally block. Regardless of the result of program execution, the finally block is always executed to ensure that the resource is closed properly.
14. Try to use shifts instead of ‘a/b’ operations
“/” is an expensive operation, and using a shift operation would be faster and more efficient
15. Try to determine the size of the StringBuffer
The constructor of a StringBuffer creates an array of characters of a default size (usually 16). In use, if this size is exceeded, memory is reallocated, a larger array is created, the original array is copied over, and the old array is discarded. In most cases, you can specify the size when creating a StringBuffer so that it doesn’t automatically grow when capacity is low, which improves performance.
16. Release references to useless objects as early as possible
Most of the time, the object referenced by a method’s local reference variable will become garbage as the method terminates, so most of the time the program does not need to explicitly set the local reference variable to NULL. Such as:
This one is not necessary. With the completion of the test method, the scope of the obJ reference variable in the program ends. But if it is changed to the following:
It is necessary to set obj to null to release references to Object as soon as possible.
17. Avoid using two-dimensional arrays whenever possible
Two-dimensional data takes up much more memory than a one-dimensional array, perhaps 10 times more.
18. Try to avoid using split
Avoid using split unless it is absolutely necessary. Because split supports regular expressions, it is relatively inefficient. If it is frequently called tens of millions of times, it will consume a lot of resources. Consider using Apache’s stringutils.split (string,char). Frequent splits can cache results.
19.ArrayList & LinkedList
One is a linear list, one is a LinkedList, in short, random queries use ArrayList as much as possible, ArrayList is better than LinkedList, LinkedList also moves Pointers, add and delete operations LinkedList is better than ArrayList, ArrayList also moves data, However, this is a theoretical analysis, the fact is not necessarily so, the important thing is to understand the data structure of the two, appropriate medicine.
20. Try to use System. Arraycopy instead of looping over arrays
Arraycopy is much faster than copying an array through a loop
21. Try to cache frequently used objects
Frequently used objects can be cached as much as possible. Arrays or containers of HashMap can be used for caching, but this method may lead to excessive cache occupation and performance deterioration. It is recommended to use some third-party open source tools such as EhCache and Oscache for caching. They basically implement FIFO/FLU and other caching algorithms.
22. Try to avoid very large memory allocations
Sometimes problems are not caused by the state of the heap at the time, but by allocation failures. The allocated blocks must all be contiguous, and as the heap gets fuller, it becomes more difficult to find large contiguous blocks.
23. Use exceptions with caution
When an exception is created, a stack track is collected that describes where the exception was created. Building these stack traces requires taking a snapshot of the runtime stack, which is very expensive. When an Exception needs to be created, the JVM has to say: Hold still, I want to save a snapshot of you as you are now, so stop pushing and pushing for a while. The stack trace contains not just one or two elements in the runtime stack, but every element in that stack.
If you create an Exception, you pay a price. Fortunately, catching exceptions is inexpensive, so you can wrap the core content around a try-catch. Technically, you can even throw exceptions at will without spending a lot of money. It is not the throw operation that incurs the performance penalty — although it is somewhat unusual to throw an exception without having previously created it. The real cost is to create the exception. Fortunately, good programming habits have taught us that we shouldn’t throw exceptions out of the window. Exceptions are designed for exceptional situations and should be used with this principle in mind.
Reuse objects whenever possible
In the case of strings in particular, use StringBuffer instead of String concatenation because not only will the system spend time generating objects, it may also spend time garbage collecting and processing them later. Therefore, generating too many objects will have a significant impact on the performance of the program.
25. Do not re-initialize variables
By default, when class constructors are called, Java initializes variables to certain values. All objects are set to null, integer variables to 0, float and double to 0.0, and logical values to false. This is especially important when a class is derived from another class, because all constructors in the constructor chain are automatically called when an object is created with the new keyword.
Public int state = this.getState; public int state = this.getState; public int state = this.getState; public int state = this.getState;
26. In the development of Java +Oracle application system
In Java +Oracle application system development, SQL language embedded in Java should be capitalized as far as possible to reduce the parsing burden of Oracle parser.
27. The I/O flow operation
In the Java programming process, database connection, I/O flow operation, after the use, timely closure to release resources. Because operating on these large objects can cause a lot of overhead.
28. Creating objects consumes a lot of system memory
Excessive object creation will consume a large amount of memory in the system, and in serious cases, will lead to memory leaks. Therefore, it is important to ensure that expired objects are recycled in a timely manner. The JVM’s GC is not very intelligent, so it is recommended that you manually set it to NULL after the object is used.
29. When using the synchronization mechanism
When using synchronization mechanisms, use method synchronization instead of code block synchronization whenever possible.
30. Do not use a Try/Catch statement in a loop. Place the Try/Catch statement in the outermost part of the loop
Error is the class that gets system errors, or virtual machine errors. Not all exceptions can be obtained. If the VM reports an Exception, the Exception cannot be obtained.
31. Using the constructor of a StringBuffer to set its initialization capacity can significantly improve performance
The default size of a StringBuffer is 16, and when the StringBuffer reaches its maximum size, it increases its size to twice its current size +2, that is, 2*n+2. Whenever StringBuffer reaches its maximum capacity, she has to create a new array of objects and then copy the old array of objects, which can waste a lot of time. So it’s important to set the StringBuffer to a reasonable initialization capacity.
32. Use java.util.Vector wisely
Vector is similar to StringBuffer in that each time it expands, all existing elements are assigned to the new storage space. Vector’s default storage capacity is 10 elements, which is doubled.
Vector.add (index,obj) inserts the element obj into the index position, but the index and subsequent elements are moved down one position (adding one to their index). Unless necessary, this is not good for performance. The same rule applies to the remove(int index) method, which removes the element at the specified position in this vector. Move all subsequent elements to the left (subtracting their index by 1). Returns the element removed from this vector. So deleting the last element of a vector is much cheaper than deleting the first element. Removing all elements is best done with the removeAllElements method.
To remove an element from a vector, use vector.remove(obj); Int index = indexOf (obj); The vector. Remove (index);
33. Create an instance of an object without using the new keyword
When an instance of a class is created with the new keyword, all constructors in the constructor chain are automatically called. But if an object implements the Cloneable interface, we can call her Clone method. The Clone method does not call any class constructors.
Here is a typical implementation of the Factory pattern:
34. HaspMap traversal
The hash value is used to extract the corresponding Entry for comparison and obtain the result. After obtaining the Entry value, the key and value are directly obtained.
— — the END — —