What are the common methods for Java code optimization?

Source: Internet
Author: User

Java code optimization is a very important step in Java programming development, Java code optimization to pay attention to detail optimization, a two-detail optimization, the effect is not small, but if everywhere can pay attention to code optimization, the code to reduce volume, improve the efficiency of the code is greatly helpful, Also to some extent to avoid unknown errors, the common Java code Optimization details are as follows:

1. Specifying the final modifier for a class or method

Specifying the final modifier for a class allows the class not to be inherited, specifying the final modifier for the method so that the method cannot be overridden, and if a class is final, all the methods of the class are final, and the Java compiler looks for the opportunity to inline all the final methods, Inline is significant for improving the efficiency of Java operations and can increase performance by an average of 50%.

2. Reuse objects as much as possible

Because Java virtual machines take time not only to generate objects, but also to take time to recycle and process these objects, generating too many objects will have a significant impact on the performance of the program.

3. Use local variables whenever possible

The arguments passed when the method is called and the temporary variables created in the call are saved in the stack, are faster, the other variables are created in the heap, are slower, and the variables created in the stack are gone, as the method runs, without additional garbage collection.

4. Close the stream in time

Java programming process, the database connection, I/O flow operation must be careful, after use, close in time to release resources, because the operation of these large objects will cause large system overhead, a little careless, will lead to serious consequences.

5. Minimize the repeated calculation of variables

In a method invocation, even if the method has only one statement, it is consumed, so you can reduce the duplicate definitions and references to the variables as you make the method calls.

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

7. Caution with exceptions

Exceptions are bad for performance because, as long as an exception is thrown, the Java Virtual machine must adjust the call stack, and the exception can only be used for error handling and should not be used to control the process.

8. Do not use Try...catch in the loop ..., it should be placed on the outermost

9. If you can estimate the length of the content to be added, specify the initial length for the collection that the underlying array implements, the tool class

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

11. Multiplication and division using shift operations

The shift operation can greatly improve performance, because at the bottom of the computer, the bitwise operation is the most convenient and fastest.

12. Do not constantly create object references within the loop

13. Based on the efficiency and type checking considerations, use the array as much as possible, and use ArrayList when the array size cannot be determined.

14. Use HashMap, ArrayList, StringBuilder as much as possible, unless required by thread safety, Hashtable, vectors, StringBuffer are not recommended, and the latter three incur performance overhead due to the use of synchronization mechanisms

15. Do not declare an array as public static final

Because this is meaningless, it simply defines the reference as static final, the contents of the array can be arbitrarily changed, and declaring the array public is a security vulnerability, which means that the array can be changed by an external class.

16. Try to use a single case in the appropriate situation

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

17. Try to avoid using static variables arbitrarily

18. Timely removal of sessions that are no longer needed

19. To implement a collection of randomaccess interfaces such as ArrayList, you should use the most common for loop instead of the Foreach Loop to traverse

20. Replacing the synchronization method with a synchronous code block

Unless you can determine that a whole method needs to be synchronized, use synchronous blocks of code as much as possible, and avoid synchronizing code that does not need to be synchronized, affecting code execution efficiency.

21. Declare a constant as static final and name it in uppercase

22. Do not create some unused objects, do not import some unused classes

23. Avoid using reflection during program operation

Reflection is powerful, but inefficient, it is not recommended to use the reflection mechanism frequently during program operation, and if it is necessary to use it, it is recommended to instantiate an object and put it into memory by reflection when the classes and projects that need to be loaded by reflection are started.

24. Using the database connection pool and the thread pool

Both pools are used to reuse objects, which avoid frequent opening and closing of connections, which avoids the frequent creation and destruction of threads.

25. IO operation with buffered input and output streams

26. Sequential insertion and random access more scenes using ArrayList, element deletions and intermediate insertions more scenes using LinkedList

27. Do not allow too many formal parameters in the public method

28. String variable and string constant equals when the string constant is written in front

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

30. Do not use the ToString () method on an array

31. Do not make a downward transition to the underlying data type that is out of range

32. Unused data in a common collection class must be removed in time

33. Convert a basic data type to a string, the base data type. ToString () is the quickest way, string.valueof (data), Data + "" slowest

34. Use the most efficient way to traverse a map

35. Separate actions for close () of resources

36. Be sure to remove the threadlocal before use or after use

37. Remember to replace the Devil's number with a constant definition, the presence of the devil's number will greatly reduce the readability of the code, and whether the string constant is defined using a constant is dependent on the case

When a long or long is initially assigned, use the uppercase L instead of the lowercase l, because the letter L is easily confused with the number 1, which is very detailed and deserves attention.

39. All overridden methods must retain @override annotations

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

41. Do not use "+" in the loop to string stitching, and directly use StringBuilder constantly append

42. Do not capture run-time exception classes defined in the Java class library that inherit from RuntimeException

43. Avoid the use of random instances by multithreading, although sharing the instance is thread-safe, but will cause performance degradation due to competition for the same seed, after JDK7, you can use Threadlocalrandom to get the random number

44. Static classes, singleton classes, factory classes set their constructors to private

The above is a common Java code optimization method, in the Java code when writing to develop the habit of code optimization, you can write small size, high efficiency, low error rate code!

What are the common methods of

Java code optimization?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.