Source: www.cnblogs.com/xrq730/p/48…
The most important function of code optimization should be to avoid unknown errors. There are a lot of unexpected errors that occur when code is up and running, and because the online environment and the development environment are very different, it’s usually a very small cause. However, in order to resolve this error, we need to self-validate, package out the class file to be replaced, suspend the service, and restart the application. For a mature project, the last one actually has a significant impact, meaning that users cannot access the application during this time. Therefore, when writing code, paying attention to details from the source, weighing and using the best options, will largely avoid unknown errors and greatly reduce the amount of work done in the long run.
The goals of code optimization are:
Reduce the size of your code
2. Improve the efficiency of code execution
Code optimization details
(1) Try to specify final modifiers for classes and methods
Classes with the final modifier are not derivable. In the Java core API, there are many examples of final applications, such as java.lang.String, where entire classes are final. Specifying a final modifier for a class makes it uninheritable, and specifying a final modifier for a method makes it unoverridden. If a class is specified as final, all methods of that class are final. The Java compiler looks for opportunities to inline all final methods. Inlining is important for improving Java runtime efficiency. See Java Runtime Optimization. This can improve performance by an average of 50%.
(2) Reuse objects as much as possible
Especially the use of String object, there should use StringBuilder/StringBuffer instead of String concatenation. Because the Java virtual machine takes time not only to generate objects, but also to garbage collect and dispose of them later, generating too many objects can have a significant impact on your program’s performance.
(3) Use local variables as much as possible
Parameters passed when a method is called, as well as temporary variables created during the call, are kept in the stack faster, while other variables, such as static variables, instance variables, and so on, are created in the heap slower. In addition, variables created in the stack are removed as the method completes its run, requiring no additional garbage collection.
(4) Close the stream in time
During Java programming, be careful when connecting to the database and performing I/O flow operations. After using the database, close the database to release resources. Because the operation of these large objects will cause a large overhead of the system, a slight mistake will lead to serious consequences.
(5) Minimize the repeated calculation of variables
Make it clear that calls to a method, even if there is only one statement in the method, have costs, including creating stack frames, protecting the scene when the method is called, and restoring the scene when the method is finished. So for example:
for (int i = 0; i < list.size(); i++) {... }Copy the code
You are advised to replace it with:
for (int i = 0, length = list.size(); i < length; i++) {... }Copy the code
This saves a lot of overhead when list.size() is large
(6) Try to use the lazy loading strategy, that is, create when needed
Such as:
String str = "aaa"; If (I == 1) {list.add(STR); }Copy the code
You are advised to replace it with:
If (I == 1) {String STR = "aaa"; list.add(str); }Copy the code
(7) Use exceptions with caution
Exceptions are detrimental to performance. To throw an exception, a new object is created. The constructor of the Throwable interface calls a locally synchronized method called fillInStackTrace(), which checks the stack to collect the call trace information. Whenever an exception is thrown, the Java virtual machine must adjust the call stack because a new object is created during processing. Exceptions should only be used for error handling and should not be used to control program flow.
(8) Do not use try… The catch… You should put it in the outermost layer
According to the opinions put forward by netizens, THIS point I think is debatable
(9) If you can estimate the length of the content to be added, specify the initial length for the underlying collection and utility class implemented as an array
Examples include ArrayList, LinkedLlist, StringBuilder, StringBuffer, HashMap, HashSet, etc. Take StringBuilder for example:
- StringBuilder()// Allocates 16 character space by default
- StringBuilder(int size)// The default allocation of size character space
- StringBuilder(String STR)// Default allocation of 16 characters +str.length() character space
You can set the initialization capacity of a class (and not just the StringBuilder above) through its constructor, which can significantly improve performance. For example, StringBuilder, length is the number of characters that the current StringBuilder can hold. Because when StringBuilder reaches its maximum capacity, it increases its current capacity by two plus two, and whenever StringBuilder reaches its maximum capacity, It would have to create a new character array and copy the contents of the old character array into the new character array — a very performance expensive operation. Imagine that the array contains about 5000 characters without specifying the length, and the nearest power of 5000 is 4096, with each increment incrementing by 2:
- Applying for 8194 character arrays on top of 4096 adds up to applying for 12290 character arrays at once, more than doubling the space saved if you could have specified 5000 character arrays initially
- Copying 4096 characters into a new character array wastes memory and reduces code efficiency. Therefore, you can’t go wrong with setting a reasonable initialization capacity for collections and utility classes that are implemented in arrays at the bottom. This will bring immediate results. Note, however, that for collections such as a HashMap, which is implemented as an array + linked list, do not set the initial size to the size you estimated, because the probability of joining only one object on a table is almost zero. The recommended initial size is 2 to the NTH power, or new HashMap(128) or new HashMap(256) if 2000 elements are expected.
(10) Run the system.arraycopy () command to copy a large amount of data
(11) Multiplication and division use shift operation
Such as:
for (val = 0; val < 100000; Val += 5) {a = val * 8; b = val / 2; }Copy the code
Using shift operation can greatly improve performance, because at the bottom of the computer, the counterpoint operation is the most convenient and fastest, so it is recommended to change to:
for (val = 0; val < 100000; Val += 5) {a = val << 3; b = val >> 1; }Copy the code
The shift operation, while fast, can make the code difficult to understand, so it is best to comment accordingly.
(12) Do not keep creating object references within the loop
Such as:
for (int i = 1; i <= count; i++)
{
Object obj = new Object();
}
Copy the code
If count is too large, the memory will be used. We recommend changing it to:
Object obj = null;
for (int i = 0; i <= count; i++)
{
obj = new Object();
}
Copy the code
Each time a new Object() is called, the Object reference refers to a different Object, but there is only one Object in memory. This saves a lot of memory.
(13) For efficiency and type checking purposes, use arrays whenever possible, and use ArrayList only when the size of the array is uncertain
(14) Use HashMap, ArrayList, and StringBuilder as much as possible. Hashtable, Vector, and StringBuffer are not recommended unless they are thread safe because they incur performance overhead due to synchronization
Do not declare arrays to be public static final
Declaring an array public is a security loophole, which means that the array can be changed by an external class
(16) Try to use singletons in appropriate situations
Singletons can reduce the load burden, shorten the load time, and improve the load efficiency. However, they are not applicable to all places. In brief, singletons are mainly applicable to the following three aspects:
- Control the use of resources, through thread synchronization to control concurrent access to resources
- Control the generation of instances to achieve the purpose of saving resources
- Control the sharing of data and allow communication between unrelated processes or threads without establishing a direct correlation
(17) Try to avoid arbitrary use of static variables
Remember that when an object is referenced by a variable defined as static, gc usually does not reclaim the heap memory occupied by the object, as in:
public class A
{
private static B b = new B();
}
Copy the code
The lifetime of the static variable B is the same as that of class A. If class A is not unloaded, the object referred to by b will stay in memory until the program terminates
(18) Delete unnecessary sessions in a timely manner
To clear out inactive sessions, many application servers have a default session timeout, typically 30 minutes. When the application server needs to hold more sessions, if the memory is low, the operating system will move some of the data to disk, the application server may dump some of the inactive sessions to disk according to the MRU (most frequently used recently) algorithm, or even throw an out-of-memory exception. If a session is to be dumped to disk, it must first be serialized, and serializing objects can be expensive in a large cluster. Therefore, when a session is no longer needed, it should be immediately cleared by calling the invalidate() method of HttpSession.
(19) Collections that implement the RandomAccess interface, such as ArrayList, should be traversed using the most common for loop rather than the foreach loop
This is what the JDK recommends to users. The RandomAccess interface is implemented to show that it supports fast RandomAccess. The main purpose of this interface is to allow general algorithms to change their behavior to provide good performance when applied to random or continuously accessed lists. Practical experience shows that the efficiency of using ordinary for loop is higher than foreach loop if the class instance implementing RandomAccess interface is accessed randomly. Conversely, if the access is sequential, it is more efficient to use Iterator. This can be done with code like the following:
if (list instanceof RandomAccess) { for (int i = 0; i < list.size(); i++){} } else { Iterator<? > iterator = list.iterable(); while (iterator.hasNext()){iterator.next()} }Copy the code
The underlying implementation principle for foreach loops is the Iterator. See Java Syntax Sugar 1: Variable-length Arguments and Foreach loops. Instead, it is more efficient to use Iterator if the class is accessed sequentially.
(20) Use synchronized code blocks instead of synchronized methods
This point has been clearly stated in the article of synchronized lock method block in multi-threaded module. Unless it can be determined that a whole method needs to be synchronized, it should try to use synchronized code block to avoid the synchronization of those codes that do not need to be synchronized, which affects the efficiency of code execution.
(21) Declare constants static final and name them in uppercase
This allows you to put the content into the constant pool at compile time, avoiding the need to evaluate the value of the generated constant at run time. In addition, it is easy to distinguish constants from variables by naming them in uppercase
(22) Do not create objects that are not used, and do not import classes that are not used
This makes no sense. If “The value of The local variable I is not used”, “The import java.util is never used” appear in your code, delete these useless things
(23) Avoid using reflection during program operation
For more information, see Reflection. Reflection is a powerful feature that Java provides to users, and powerful features often mean inefficient. It is not recommended to use invoke methods that use reflection frequently, especially Method, during program execution. If necessary, One suggested approach is to have classes that need to be loaded by reflection instantiate an object by reflection and put it into memory at project startup — the user only cares about getting the fastest response time when interacting with the peer side, not how long it takes the peer side to start the project.
(24) Use database connection pools and thread pools
Both pools are designed to reuse objects, the former to avoid frequent opening and closing of connections, and the latter to avoid frequent thread creation and destruction
(25) Use buffered I/O streams for IO operations
Buffered input and output streams (BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream) can greatly improve I/O efficiency
(26) ArrayList is used for scenarios with high sequential insertion and random access, and LinkedList is used for scenarios with high element deletion and intermediate insertion
Understand how ArrayList and LinkedList work
Don’t let public methods have too many parameters
Public methods are methods that are provided externally. There are two main disadvantages to giving them too many parameters:
- It violates the idea of object-oriented programming, because Java insists that everything is an object, and too many parameters, and object-oriented programming doesn’t fit
- Too many parameters will inevitably increase the probability of error in method calls
As for how many “too many” means, three or four. For example, if we write an insertStudentInfo method in JDBC and have 10 Student fields to insert into the Student table, we can wrap these 10 parameters in an entity class as parameters to the insert method
String variables and string constants equals before string constants
This is a common trick if you have the following code:
String str = "123";
if (str.equals("123"))
{
...
}
Copy the code
You are advised to change the value to:
String str = "123";
if ("123".equals(str))
{
...
}
Copy the code
This is mostly to avoid null-pointer exceptions
In Java, if (I == 1) is the same as if (1 == I)
“If (I ==1)” is different from “if(1== I)”.
In C/C++, the “if (I ==1)” criterion is valid, based on 0 and non-0, 0 means false, non-0 means true, if there is such a code:
int i = 2;
if (i == 1)
{
...
}
else
{
...
}
Copy the code
C/C++ determines that “I ==1” is not true, so 0 is false. But if:
int i = 2;
if (i = 1)
{
...
}
else
{
...
}
Copy the code
If a programmer accidentally writes “if(I ==1)” as “if(I =1)”, then there’s a problem. If (I = 1); if (I = 1); if (I = 1); This can happen in C/C++ development and can lead to some unintelligible errors, so to avoid incorrect assignments in if statements, it is recommended to write if statements as:
int i = 2;
if (1 == i)
{
...
}
else
{
...
}
Copy the code
This way, even if the developer accidentally writes “1= I”, the C/C++ compiler can detect it in the first place, because we can assign I to a variable, but we cannot assign 1 to a constant.
The C/C++ syntax “if(I =1)” is not possible in Java, however, because it would cause Java to compile an error “Type Mismatch: Cannot convert from int to Boolean”. However, although there is no semantic difference between “if (I == 1)” and “if (1 == I)” in Java, the former is better recommended as a matter of reading habit.
Do not use the toString() method on arrays
Take a look at what is printed using toString() on an array:
public static void main(String[] args)
{
int[] is = new int[]{1, 2, 3};
System.out.println(is.toString());
}
Copy the code
The result is:
[I@18a992f
Copy the code
The null pointer exception is possible because the array reference is null. AbstractCollections overrides the toString() method of Object, but it doesn’t make sense to print the contents of the collection toString().
(31) Do not force downcasts of primitive data types that are out of scope
This will never get the desired result:
public static void main(String[] args)
{
long l = 12345678901234L;
int i = (int)l;
System.out.println(i);
}
Copy the code
We might expect some of them, but the result is:
1942892530
Copy the code
Explain. In Java, long is 8 bytes 64-bit, so 12345678901234 should look like this:
0000 0000 0000 0000 0000 1011 0011 1010 0111 0011 1100 1110 0010 1111 1111 0010
Copy the code
The first 32 bits of an int are the same as the first 32 bits of an int:
0111 0011 1100 1110 0010 1111 1111 0010
Copy the code
This string of binary is represented as decimal 1942892530, so that’s what our console output is above. Two further conclusions can be drawn from this example:
Int l = 12345678901234L (12345678901234L, 12345678901234L, 12345678901234L); By the way, the default floating-point type is double, so you define float as “float f = 3.5f”
Int ii = l + I; An error is reported because long + int is a long and cannot be assigned to int
(32) The public collection class does not use the data must be removed in time
If a collection class is public (that is, not an attribute in a method), the elements in the collection are not automatically freed because there are always references to them. Therefore, if some data in the public set is not used but not removed, it will cause the public set to increase, so that the system has the potential of memory leakage.
ToString () is the fastest method, followed by String.valueof (data), and data + “” is the slowest
There are three general ways to convert a basic datatype. I have an Integer datatype I, and I can use i.tostring (), string.valueof (I), and I +.
public static void main(String[] args) { int loopTime = 50000; Integer i = 0; long startTime = System.currentTimeMillis(); for (int j = 0; j < loopTime; j++) { String str = String.valueOf(i); } system.out.println (" string.valueof () : "+ (system.currentTimemillis () -startTime) + "ms"); startTime = System.currentTimeMillis(); for (int j = 0; j < loopTime; j++) { String str = i.toString(); } system.out.println (" integer.toString () : "+ (system.currentTimemillis () -startTime) + "ms"); startTime = System.currentTimeMillis(); for (int j = 0; j < loopTime; j++) { String str = i + ""; } system.out.println (" I + \"\" : "+ (system.currentTimemillis () -startTime) + "ms"); }Copy the code
The running results are as follows:
String.valueof () : 11ms Integer.toSTRING () : 5ms I + "" : 25msCopy the code
Therefore, the toString() method will be preferred when converting a primitive data type toString. As for why, it’s simple:
- The string.valueof () method calls integer.tostring () underneath, but shorts the judgment before calling it
- The integer.toString () method is called instead
- The bottom layer of I + “” is implemented with StringBuilder. Append method is used first, and then toString() method is used to get the string
Compared with the three, it is obvious that 2 is the fastest, 1 is the second, and 3 is the slowest
(34) Use the most efficient way to traverse the Map
There are many ways to traverse a Map. Generally, we need to traverse keys and values in a Map. The most efficient way is recommended as follows:
public static void main(String[] args) { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("111", "222"); Set<Map.Entry<String, String>> entrySet = hm.entrySet(); Iterator<Map.Entry<String, String>> iter = entrySet.iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); System.out.println(entry.getKey() + "\t" + entry.getValue()); }}Copy the code
If you just want to iterate over the Map’s keys, use “Set keySet = hm.keyset ();” Would be more appropriate
It is recommended to separate resource close()
So let’s say I have a piece of code like this:
try
{
XXX.close();
YYY.close();
}
catch (Exception e)
{
...
}
Copy the code
You are advised to change the value to:
try
{
XXX.close();
}
catch (Exception e)
{
...
}
try
{
YYY.close();
}
catch (Exception e)
{
...
}
Copy the code
It’s a hassle, but it avoids resource leaks. Yyy. close() will not be executed, and YYY will not be recycled. It has been used for a long time. This code may cause resource handle leakage. XXX and YYY will be closed in any case
Remove ThreadLocal before or after use
Almost all current projects use thread pooling technology, which is great because you can dynamically configure the number of threads and reuse threads.
However, if you use ThreadLocal in your project, be sure to remove it before or after using it. This is because the thread pool technique mentioned above does a thread reuse, which means that while code is running, a thread that has been used is not destroyed but is waiting for another use. We have a look at the Thread class, holding a ThreadLocal. ThreadLocalMap references:
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
Copy the code
Article on the Thread does not destroy means the Thread set ThreadLocal. Data in a ThreadLocalMap still exists, then the next a Thread to reuse the Thread, is likely to get to is a Thread on the set of data rather than the content they want.
This is a very subtle problem, and it is very difficult to find errors due to this cause without experience or solid foundation, so pay attention to this when writing code, which will save you a lot of work later on.
(37) Remember to replace devil numbers with constant definitions. Devil numbers can greatly reduce code readability
(38) The initial assignment of long or long is to use a capital L instead of a lowercase L, because the letter L can easily be confused with the number 1. This point is worth noting in detail
All overridden methods must retain the @override annotation
There are three reasons to do this:
(1) It is clear that this method is inherited from the parent class
(2) getObject() and get0bject(), the former is the fourth letter of “O”, the latter is the fourth parent of “0”, add @override annotation can immediately determine whether the rewrite is successful
(3) If the method signature is modified in the abstract class, the implementation class will immediately report a compilation error
(40) It is recommended to use the new Objects utility class introduced in JDK7 to compare the equals of Objects, directly a.equals(b), with the risk of null pointer exceptions
Instead of using “+” for string concatenation in the loop, use StringBuilder to append the string
To explain why I don’t use “+” for string concatenation, suppose I had a method:
public String appendStr(String oriStr, String... appendStrs) {
if (appendStrs == null || appendStrs.length == 0) {
return oriStr;
}
for (String appendStr : appendStrs) {
oriStr += appendStr;
}
return oriStr;
}
Copy the code
Decompile this code into the.class file using Javap -C and intercept the key parts:
This means that every time the virtual machine encounters the “+” operator to concatenate strings, it creates a New StringBuilder, calls append, and then toString() to convert the string to an oriStr object. How many StringBuilder() will be new, which is a waste of memory.
(42) Do not catch run-time exception classes defined in the Java class library that inherit from RuntimeException
Exception handling is inefficient and RuntimeException classes are RuntimeException classes, most of which can be completely circumvented by programmers, such as:
- ArithmeticException can be circumvented by determining whether the divisor is empty
- NullPointerException can be circumvented by determining whether an object is empty
- IndexOutOfBoundsException can be avoid by judging the array/string length
- ClassCastException can be circumvented using the instanceof keyword
- ConcurrentModificationException can use iterator to evade
(43) Avoid Random instance being used by multiple threads. Although sharing this instance is thread safe, it will degrade performance due to competing with the same seed. After JDK7, ThreadLocalRandom can be used to obtain Random numbers
To explain why competing for the same seed causes performance degradation, for example, look at the nextInt() method implementation of the Random class:
public int nextInt() {
return next(32);
}
Copy the code
Next (int bits) is called, which is a protected method:
protected int next(int bits) { long oldseed, nextseed; AtomicLong seed = this.seed; do { oldseed = seed.get(); nextseed = (oldseed * multiplier + addend) & mask; } while (! seed.compareAndSet(oldseed, nextseed)); return (int)(nextseed >>> (48 - bits)); }Copy the code
The seed here is a global variable:
/**
* The internal state associated with this pseudorandom number generator.
* (The specs for the methods in this class describe the ongoing
* computation of this value.)
*/
private final AtomicLong seed;
Copy the code
When multiple threads simultaneously acquire random numbers, they will compete for the same seed, resulting in a decrease in efficiency.
Static, singleton, and factory classes make their constructors private
This is because static classes, singleton classes, factory classes, and so on do not need to be externally new in the first place. Making the constructor private ensures that these classes do not generate instance objects.
Afterword.
Good code comes from every little bit of optimization, paying attention to every detail, not only can improve the efficiency of the program, but also can avoid many unknown problems.
Recommended reading
Resources: Ten stages of learning to become an architect!
Tutorials: The most powerful Spring Boot & Cloud tutorials ever
Tools: Recommended an online creation flow chart, mind mapping software
Scan and follow our wechat official account, reply “666” to get a set of Java concurrent programming HD video tutorial.