Some experience in Java code optimization sharing!

Source: Internet
Author: User

1, as far as possible to specify the final modifier class, method

A class with the final modifier is not derived. In the Java Core API, there are many examples of final application, such as java.lang.String, where the entire class is final. Specifying the final modifier for a class allows a class not to be inherited, and specifying the final modifier for a method can allow the method to be overridden. If you specify that a class is final, all methods of that class are final. The Java compiler looks for opportunities to inline all final methods, and inline is important for improving the efficiency of Java operations, as detailed in Java runtime optimizations. This will increase performance by an average of 50%.

2. Reuse objects as much as possible

In particular, the use of String objects should be replaced with stringbuilder/stringbuffer when strings are concatenated. Because Java virtual machines not only take time to generate objects, they may also take time to garbage collect and process these objects, so 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 invoked and the temporary variables created in the call are saved in the stack faster, and 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 is run over, are gone and no additional garbage collection is required.

4, in time to close the flow

Java programming process, the database connection, I/O flow operation must be careful, after the use, timely shutdown to release resources. Because the operation of these large objects will cause a large system overhead, a slight carelessness, will lead to serious consequences.

5, minimize the duplication of the calculation of variables

Clear a concept, the call to the method, even if only one sentence in the method, is also consumed, including the creation of stack frames, call methods to protect the scene, when the method is completed to restore the scene. So for example, the following actions:

for (int i = 0; i < list.size (); i++)

{...}

Suggested replacements are:

for (int i = 0, length = list.size (); i < length; i++)

{...}

In this way, when the list.size () is very large, it reduces a lot of consumption

6, try to use lazy load strategy, that is, when needed to create

For example:

String str = "AAA";

if (i = = 1)

{

List.add (str);

}

Suggested replacements are:

if (i = = 1)

{

String str = "AAA";

List.add (str);

}

7, careful use of abnormal

Exceptions are bad for performance. Throwing an exception first creates a new object, the constructor of the Throwable interface calls a local synchronization method named Fillinstacktrace (), and the Fillinstacktrace () method checks the stack to collect call tracking 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 to control the process.

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

According to the comments made by netizens, I think it is worth discussing

9, if you can estimate the length of content to be added, for the bottom of the array implementation of the collection, tool class to specify the initial length

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

You can set its initialization capacity by the constructor of a class (not just the StringBuilder above), which can significantly improve performance. For example, StringBuilder, length represents the number of characters the current StringBuilder can hold. Because when StringBuilder reaches its maximum capacity, it increases its capacity to the current twice-fold plus 2, and whenever the StringBuilder reaches its maximum capacity, it has to create a new character array and then copy the old character array contents to the new character array-- This is a very performance-intensive operation. Just imagine, if you can estimate the character array to store 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 for a 8,194-size character array, add up to apply for a 12,290-size character array, if the beginning can specify 5,000 size of the character array, save more than one time space

(2) Copy the original 4,096 characters into a new character array

In this way, both waste memory space and reduce the efficiency of code operation. Therefore, it is not correct to set a reasonable initialization capacity for the underlying array and the tool class, which will result in an immediate effect. But note, like HashMap, this is a collection of array + linked lists, and don't set the initial size to the size you estimate, because the probability of connecting only one object on a table is almost 0. The initial size is proposed to be set to the N-Power of 2, if you can estimate 2000 elements, set to new HashMap (128), new HASHMAP (256) can be.

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.