Java code optimization, what are the common methods?

  Java code optimization is a very important step in Java programming development. Java code optimization should pay attention to detail optimization. The optimization of one or two details will produce little effect, but if you can pay attention to code optimization everywhere, it will reduce the size of the code and improve the The efficiency of code operation is of great help, and it can also avoid unknown errors to a certain extent. The commonly used Java code optimization details are as follows:

  1. Specify final modifiers for classes and methods

  Specifying the final modifier for a class can make the class non-inheritable, and specifying the final modifier for a method can prevent the method from being overridden. If a class is specified as final, all methods of the class are final, and Java compiles. The compiler will look for opportunities to inline all final methods. Inlining plays a significant role in improving the efficiency of Java, which can increase performance by an average of 50%.

  2. Reuse objects as much as possible

  Since the Java virtual machine not only takes time to generate objects, but also takes time to garbage collect and process these objects, generating too many objects will have a great impact on the performance of the program.

  3. Use local variables whenever possible

  The parameters passed when calling the method and the temporary variables created in the call are stored in the stack, which is faster, and other variables are created in the heap, which is slower, and the variables created in the stack, as the method ends, The content is gone, no extra garbage collection.

  4. Close the stream in a timely manner

  In the process of Java programming, you must be careful when performing database connection and I/O stream operations. After using it, close it in time to release resources, because the operation of these large objects will cause a lot of overhead to the system. lead to serious consequences.

  5. Minimize double counting of variables

  In a method call, even if the method has only one statement, it is still consuming. Therefore, the repeated definitions and references to variables can be reduced as much as possible when making a method call.

  6. Try to use a lazy loading strategy, that is, create it when needed

  7. Use exceptions with caution

  Exceptions are bad for performance because the Java virtual machine has to adjust the call stack whenever an exception is thrown, exceptions should only be used for error handling and should not be used to control program flow.

  8. Don't use try...catch... in a loop, put it at the outermost level

  9. If the length of the content to be added can be estimated, specify the initial length for the underlying collection and tool class implemented in the form of an array

  10. When copying large amounts of data, use the System.arraycopy() command

  11. Multiplication and division using shift operations

  Using shift operations can greatly improve performance, because at the bottom of the computer, bitwise operations are the most convenient and fastest.

  12. Don't keep creating object references in loops

  13. Based on the consideration of efficiency and type checking, array should be used as much as possible, and ArrayList should be used only when the size of the array cannot be determined.

  14. Try to use HashMap, ArrayList, and StringBuilder. Unless thread safety is required, Hashtable, Vector, and StringBuffer are not recommended. The latter three cause performance overhead due to the use of synchronization mechanisms.

  15. Do not declare arrays as public static final

  Because this is meaningless, it just defines the reference as static final, the contents of the array can still be changed at will, and declaring the array as public is a security hole, which means that the array can be changed by external classes.

  16. Try to use singletons where appropriate

  In the case of controlling the use of resources, the generation of control instances, and the sharing of control data, singletons can be used to reduce the burden of loading, shorten the time of loading, and improve the efficiency of loading.

  17. Try to avoid arbitrary use of static variables

  18. Clear sessions that are no longer needed in a timely manner

  19. Collections that implement the RandomAccess interface, such as ArrayList, should be traversed using the most common for loop instead of a foreach loop

  20. Use synchronized code blocks instead of synchronized methods

  Unless you can determine that an entire method needs to be synchronized, try to use synchronized code blocks to avoid synchronizing code that does not need to be synchronized, which affects the efficiency of code execution.

  21. Declare constants as static final and name them in uppercase

  22. Don't create some unused objects, don't import some unused classes

  23. Avoid using reflection during program execution

  Reflection has powerful functions, but its efficiency is not high. It is not recommended to use the reflection mechanism frequently during the running of the program. If you really need to use it, it is recommended to instantiate an object through reflection when the classes and projects that need to be loaded through reflection are started and placed into memory

  24. Use database connection pool and thread pool

  Both of these pools are used to reuse objects, the former avoids opening and closing connections frequently, and the latter avoids creating and destroying threads frequently.

  25. Use buffered input and output streams for IO operations

  26. Use ArrayList for scenes with more sequential insertion and random access, and use LinkedList for scenes with more element deletion and intermediate insertion

  27. Don't have too many parameters in public methods

  28. When string variables and string constants are equals, write string constants in front

  29. There is no difference between if (i == 1) and if (1 == i) in java, but from reading habits, it is recommended to use the former

  30. Don't use toString() on arrays

  31. Do not downcast to out-of-scope primitive data types

  32. The data not used in the public collection class must be removed in time

  33. Convert a basic data type to a string, basic data type.toString() is the fastest way, String.valueOf(data) is the second, data+"" is the slowest

  34. Use the most efficient way to traverse the Map

  35. Close() on resources is recommended to operate separately

  36. Be sure to remove before or after using ThreadLocal

  37. Remember to replace devil numbers with constant definitions. The existence of devil numbers will greatly reduce the readability of the code. Whether string constants use constant definitions can depend on the situation.

  38. When initializing a long or Long, use an uppercase L instead of a lowercase l, because the letter l is easily confused with the number 1. This point is very detailed and worth noting

  39. All overridden methods must retain the @Override annotation

  40. It is recommended to use the Objects tool class newly introduced in JDK7 to perform equals comparison of objects, directly a.equals(b), there is a risk of null pointer exception

  41. Don't use "+" for string concatenation in the loop body, but directly use StringBuilder to append continuously

  42. The runtime exception class defined in the Java class library that inherits from RuntimeException is not caught

  43. Avoid the use of Random instances by multiple threads. Although sharing the instance is thread-safe, it will cause performance degradation due to competition for the same seed. After JDK7, you can use ThreadLocalRandom to obtain random numbers.

  44. Static classes, singleton classes, and factory classes make their constructors private

 

  The above are the commonly used Java code optimization methods. If you develop the habit of code optimization when writing Java code, you can write code with small size, high operating efficiency and low error rate!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326122964&siteId=291194637