Summary of 35 Java code performance optimizations (1)
Preface
Code optimization is a very important topic. Some people may think it is useless. In some small places, what are the effects of modifying or not modifying the code on the code running efficiency? I think so. Is it useful to eat a small shrimp like a whale in the sea? It's useless, but after eating more than one shrimp, the whale will be fed. The same is true for code optimization. If the project focuses on getting online without bugs as soon as possible, you can minimize the size of the code and refine the code details. However, if you have enough time to develop and maintain the code, at this time, every detail that can be optimized must be considered. A small number of optimization points are accumulated, which definitely improves the code running efficiency.
The goal of code optimization is:
1. reduce the size of the Code
2. Improve code running efficiency
Code optimization details
1. Specify the final modifier of classes and methods whenever possible.
Classes with final modifiers cannot be derived. In Java core APIs, there are many examples of final applications, such as java. lang. String. The entire class is final. Specifying a final modifier for a class prevents the class from being inherited, and specifying a final modifier for the method prevents the method from being overwritten. If a class is specified as final, all methods of the class are final. The Java compiler will look for opportunities to inline all final methods. inline plays a major role in improving Java runtime efficiency. For details, see Java runtime optimization. This can increase the performance by an average of 50%.
2. Try to reuse objects
In particular, the use of String objects should be replaced by StringBuilder/StringBuffer when a String connection occurs. The Java virtual machine not only takes time to generate objects, but may also take time to recycle and process these objects. Therefore, generating too many objects will greatly affect the program performance.
3. Use local variables whenever possible
Parameters passed during method call and temporary variables created in the call are saved in the stack at a high speed. other variables, such as static variables and instance variables, are created in the heap, slow speed. In addition, the variables created in the stack are no longer needed as the method stops running, and no additional garbage collection is required.
4. Close the stream in time
During Java programming, be careful when performing database connection and I/O Stream operations. after use, close the service in time to release resources. Because the operations on these large objects will cause a large overhead of the system, and a slight carelessness will lead to serious consequences.
5. Reduce repeated variable calculation as much as possible
Define a concept and call a method, even if there is only one statement in the method, it is consumption, this includes creating stack frames, protecting the site when calling methods, and restoring the site when calling methods are completed. For example:
- For (int I = 0; I <list. size (); I ++)
-
- {...}
-
- We recommend that you replace it:
-
- For (int I = 0, int length = list. size (); I <length; I ++)
-
- {...}
In this way, when list. size () is large, a lot of consumption is reduced.
6. Try to adopt the lazy loading policy, that is, create it only when necessary.
For example:
- String str = "aaa";if (i == 1)
- {
-
- list.add(str);
-
- }
We recommend that you replace it:
- if (i == 1)
- {
-
- String str = "aaa";
-
- list.add(str);
-
- }
7. Use exceptions with caution
Exceptions are detrimental to performance. To throw an exception, you must first create a new object. The constructor of the Throwable interface calls the local synchronous method named fillInStackTrace (). The fillInStackTrace () method checks the stack and collects Call trace information. As long as an exception is thrown, the Java Virtual Machine must adjust the call stack because a new object is created during processing. Exceptions can only be used for error handling and should not be used to control program processes.
8. Do not use try… in a loop... Catch ..., Put it in the outermost layer
Unless you have. If you write this code for no reason, as long as your senior leader has a little bit of obsessive-compulsive disorder, will scold you for writing such spam code.
9. If you can estimate the length of the content to be added, specify the initial length for the collection and tool class implemented in array mode at the underlying layer.
For example, ArrayList, LinkedLlist, StringBuilder, StringBuffer, HashMap, and HashSet. Take StringBuilder as an example:
- 1) StringBuilder () // a space of 16 characters is allocated by default.
-
- 2) StringBuilder (int size) // space allocated with size characters by default
-
- 3) StringBuilder (String str) // by default, 16 characters + str. length () are allocated.
You can set the initialization capacity of the class by referring to not only the StringBuilder above, which can significantly improve the performance. For example, StringBuilder. length indicates the number of characters that can be maintained by the current StringBuilder. Because when StringBuilder reaches the maximum capacity, it will increase its capacity to 2 times the current capacity and 2 times, whenever StringBuilder reaches its maximum capacity, it has to create a new character array and copy the content of the old character group to the new character array-this is a very performance-consuming operation. Imagine if we can estimate that the character array contains 5000 characters rather than the specified length, and the power of 2 power closest to 5000 is 4096. If we add 2 to each expansion, then:
1) on the basis of 4096, apply for an array of 8194 characters, which is equivalent to applying an array of 12290 characters at a time. If you can specify an array of 5000 characters at the beginning, it saves more than doubled the space.
2) copy the 4096 characters to the new character array.
In this way, the memory space is wasted and the code running efficiency is reduced. Therefore, it is impossible to set a reasonable initial capacity for the collection and tool classes implemented by arrays at the underlying layer, which will bring immediate results. However, note that, for example, HashMap is a set implemented by arrays and linked lists. Do not set the initial size to the same as your estimated size, because the possibility of connecting only one object on a table is almost 0. We recommend that you set the initial size to the N power of 2. If you can estimate that there are 2000 elements, set them to new HashMap (128) and new HashMap (256.
10. When copying a large amount of data, use the System. arraycopy () command