Java Code Optimization Summary

Source: Internet
Author: User

Code optimization is a very important topic. In general, the goal of code optimization is mainly two, one is to reduce the size of the code, and the other is to improve the efficiency of code operation.

There are many details of code optimization, and here are some examples:

1 . Specify the final modifier of the class and method as much as possible.

A class with a final modifier is not derived. In the Java Core API, there are many examples of final applications, such as Java.lang.String, where the entire class is final.

Specifying the final modifier for a class allows the class not to be inherited, and specifying the final modifier for a method allows the method not to be overridden.

If a class is specified as final, all methods of the class are final.

The Java compiler will look for opportunities to inline all of the final methods, and inline is significant for improving the efficiency of Java operations.

2. Reuse objects as much as possible

In particular, the use of String objects should be replaced with stringbuilder/stringbuffer when strings are concatenated. stringbuffer is thread-safe, but less efficient than thread -insecure StringBuilder, so if it is not multithreaded, it is recommended to use the StringBuilder.

Because Java virtual machines take time not only to generate objects, but may also take time to garbage-collect and process them later, generating too many objects will have a significant impact on the performance of the program.

3. Use local variables whenever possible

The parameters passed when the method is called and the temporary variables created in the call are saved in the stack and are faster; other variables, such as static variables, instance variables, etc., are created in the heap and are slower.

In addition, the variables created in the stack, as the method runs, are gone, and no additional garbage collection is required.

4. Close the flow in time

In the Java programming process, the database connection, I/O flow operation must be careful, when the use is complete, close in time to release resources. Because the operation of these large objects can cause large overhead, and a slight carelessness, will result in serious consequences.

5, minimize the repetition of the variable calculation

To define a concept, the invocation of a method, even if there is only one sentence in the method, is also consumed, including creating a stack frame, protecting the site when invoking a method, recovering the site when the method is called, and so on. So for example, the following actions:

6, in the use of a single case mode, try to use lazy-loading strategies, which are created when needed.

7. Caution with Exceptions

Exceptions are bad for performance. Throws an exception first to create a new object, the constructor of the Throwable interface calls the local synchronization method named Fillinstacktrace (), the Fillinstacktrace () method examines the stack, and collects 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 the process. Exceptions can only be used for error handling and should not be used for control procedures.

8, do not use Try...catch in the loop ..., you should put it on the outermost

Unless there is a last resort. If you have no reason to write this, as long as your leader, a bit of obsessive-compulsive disorder, probably will scold you why write this garbage code.

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

such as ArrayList, Linkedllist, StringBuilder, StringBuffer, HashMap, HashSet, etc., take StringBuilder as an example:

(1) StringBuilder ()//16-character space is assigned by default

(2) StringBuilder (int size)//space with size characters assigned by default

(3) StringBuilder (String str)//default 16 characters +str.length () character space

It is possible to set its initialization capacity through the class's default allocation space, which can significantly improve performance. For example, Stringbuilder,length indicates the number of characters the current StringBuilder can hold. Because when the StringBuilder reaches its maximum capacity, it will increase its capacity to the current twice times plus 2, whenever StringBuilder reaches its maximum capacity, it will have to create a new character array, and then copy the old character array contents into the new character array, This is an operation that is very expensive to perform. Imagine, if you can estimate the character array to hold about 5,000 characters without specifying the length, the nearest 5000 of the 2 power is 4096, each expansion plus 2 regardless, then:

(1) on the basis of 4096, and then apply 8,194 size of the character array, add up to the equivalent of a 12,290-size character array, if you can initially specify a 5,000-size character array, saving more than a space

(2) Copy the original 4,096 characters into the new character array. In this way, both the memory space is wasted and the code runs efficiently.

Therefore, it is wrong to set a reasonable initialization capacity for the collection and tool class of the underlying array implementation, which will bring an immediate effect. Note, however, that a collection like HashMap is implemented as an array + linked list, so do not set the initial size to the size you estimate because it is almost 0 more likely to connect an object on a table. The initial size proposal is set to the power of N of 2, which can be set to new HashMap (128), and new HashMap (256) if it can be estimated to have 2000 elements.

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. In addition, the shift operation is fast, but may make the code less well understood, so it is best to add the appropriate comments.

12. do not constantly create object references within a loop

  This practice causes the memory to have count copies of the object reference to exist, and if count is large, it consumes memory. There should be only one copy of the object object in memory, and each time new object () is referenced, the object reference points to a different object, but there is only one copy in memory, which saves memory space considerably.

13, based on the efficiency and type checking considerations, should use as far as possible array, cannot determine the size of the array to use ArrayList

14, as far as possible to use HashMap, ArrayList, StringBuilder, unless the need for thread safety, it is not recommended to use Hashtable, Vector, StringBuffer, the latter three due to the use of synchronization mechanism resulting in a large performance overhead.

15. Do not declare the 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

Using a single example can reduce the load burden, shorten the load time, improve the efficiency of loading, but not all places are applicable to a single case, simply speaking, the single case is mainly applicable to the following three aspects:

(1) Control the use of resources, through thread synchronization to control the resources of concurrent access.

(2) control the production of examples, in order to achieve the purpose of saving resources.

(3) Control the sharing of data, in the condition of not establishing a direct association, let a number of unrelated processes or threads to achieve communication between.

17, try to avoid arbitrary use of static variables

You know, when an object is referenced by a variable defined as static, the GC usually does not reclaim the heap memory that the object occupies, thereby unnecessarily increasing the memory overhead.

18. clean up sessions that are no longer needed

In order to clear a session that is no longer active, many application servers have a default session timeout, which typically takes 30 minutes. When the application server needs to save more sessions, if there is not enough memory, the operating system will transfer some of the data to disk, and the application server may dump partially inactive sessions to disk based on the MRU (most recently used) algorithm, and may even throw out-of-memory exceptions. If a session is to be dumped to disk, it must be serialized first, and the cost of serializing the object is expensive in a large-scale cluster. Therefore, when the session is no longer needed, the httpsession invalidate () method should be called in time to clear the session.

19, the implementation of the Randomaccess interface, such as ArrayList, should use the most common for loop instead of the Foreach Loop to traverse

This is what the JDK recommends to the user. The JDK API's explanation for the Randomaccess interface is that the implementation of the Randomaccess interface is used to indicate that it supports fast random access, and the primary purpose of this interface is to allow a generic algorithm to change its behavior so that it can provide good performance when applied to random or contiguous access lists. The actual experience shows that the class instance that implements the Randomaccess interface, if it is random access, uses the normal for loop efficiency higher than the Foreach loop, and conversely, if it is accessed sequentially, the use of iterator is more efficient.

  The underlying implementation of the Foreach loop is the iterator iterator.

20. Use synchronous code block instead of synchronization method

Unless you can determine that the entire 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, which can affect code execution efficiency.

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

This allows the content to be placed in a constant pool during compilation, avoiding the value of the generated constant during run time. In addition, you can easily distinguish constants from variables by naming them in uppercase.

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

This does not make sense if the code appears "the value of the local variable I am not used", "the import java.util is never used", then remove these useless content.

23. Avoid using reflection during program operation

Reflection is a powerful feature that Java provides to users, and powerful often means less efficient. It is not recommended to use during a program's operation, especially with the frequent use of the reflection mechanism, especially the Invoke method of method, and if it is necessary, a recommended practice is to increase the efficiency by instantiating an object and putting it into memory when the project is started by reflection by reflecting the class that needs to be loaded by reflection. After all, the user only cares about the fastest response time when interacting with the peer, and doesn't care how long it takes to start the project on the end.

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/output stream

Buffered input and output streams, BufferedReader, BufferedWriter, Bufferedinputstream, and bufferedoutputstream, can greatly improve IO efficiency.

26, sequential insertion and random access to more scenes using ArrayList, element deletion and intermediate insertions more scenes using LinkedList.

27. Do not let the public method have too many formal parameters

The public method is a method provided externally, and there are two disadvantages to giving these methods too many parameters:

(1) in violation of object-oriented programming ideas, Java emphasizes that everything is object, too many formal parameters, and object-oriented programming ideas do not fit.

(2) Too many parameters will inevitably cause the error probability of the method call to increase.

For example, we use JDBC to write a insertstudentinfo method, there are 10 student information fields to be inserted into the student table, you can encapsulate these 10 parameters in an entity class (such as the set set), as the parameter of the Insert method.

28, string variable and string constant equals when the string constant is written in front, so that you can avoid null pointer exceptions.

29. Although Java's "if (i = = 1)" and "if (1 = = i)" Have no semantic differences, it is better to use the former in terms of reading habits.

  30. Do not use the ToString () method for arrays, either outputting the address of the array or possibly causing null pointer exceptions because the array is empty. If you want to enumerate through the elements of the group arr, you can use Arrays.tostring (arr) directly.

31. Do not make a downward shift in the underlying data types that are out of scope, which often results in a loss of precision.

32. data that is not used in a common collection class must be removed in time

If a collection class is public, the elements inside the collection are not automatically freed because references are always directed to them. Therefore, if some of the data in a common collection is not used without going to remove them, it will cause this common set to grow, causing the system to have a hidden memory leak.

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

this is due to: The integer.tostring () method is called at the bottom of the string.valueof () method, but the judgment is short before the call, such as the Integer.tostring () method can be called directly; I + "", The underlying uses the StringBuilder implementation, first stitching with the Append method, and then using the ToString () method to get the string.

By contrast, the three are clearly toString () fastest, string.valueof , Data + "" slowest,

34. use the most efficient way to traverse a map

There are many ways to traverse a map, and the most common scenario we need is to traverse the key and value in the map, so the most efficient way to use it is:

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 ());}}

If you just want to traverse the key value of a map, it would be more appropriate to do this:

Set KeySet = Hm.keyset ();

35, the Close () to the resources proposed separate operation

Try{xxx.close (); Yyy.close ();} catch (Exception e) {...} Suggested changes to: try{Xxx.close ();} catch (Exception e) {...} try{yyy.close ();} catch (Exception e) {...}

Although there is some trouble, it can avoid resource leakage. Imagine, if there is no modified code, in case Xxx.close () thrown out of the exception, then entered the Cath block, Yyy.close () will not execute, YYY this resource will not be recycled, has been occupied, such a lot of code, is likely to cause the disclosure of resource handle. And instead of the following wording, it is guaranteed that XXX and yyy will be close off anyway.

36, careful use of recursion (as far as possible)

Recursion increases the stack memory overhead, which can easily cause a stack memory overflow exception.

Java Code Optimization Summary

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.