35 Java Development Code Performance optimization Summary __java

Source: Internet
Author: User
Tags error handling garbage collection int size modifier reflection sessions stringbuffer

Preface

Code optimization, a very important topic. Some people may feel useless, some small places have what good to modify, and do not change the operation of the Code to the efficiency of what impact it. This question I think so, like the whale in the sea, it is useful to eat a small shrimp. No use, but after eating a lot of shrimp, the whale is fed. The same is true with code optimization, if the project is focused on no bugs as soon as possible, then you can grasp the small, the details of the code can not fine grinding; but if you have enough time to develop and maintain your code, then you have to consider every detail that can be optimized, and a tiny optimization point accumulates, There is definitely an increase in the efficiency of your code.

The goal of code optimization is:

1, reduce the size of the code

2, improve the efficiency of code operation

Code Optimization Details 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, int 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&hellip;catch&hellip in the cycle, you should put it in the outermost

Unless it's a last resort. If you have no reason to write this, as long as your leadership senior, there is a compulsion to scold you why you write this garbage code to 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:

(1) StringBuilder ()///default allocation of 16 characters space

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

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

The initialization capacity can be set by the 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 the 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 &mdash;-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. 10. When copying large amounts of data, use the system.arraycopy () command 11. Multiplication and division use shift operations

For example:

for (val = 0; Val < 100000; val = 5)

{

A = Val * 8;

b = VAL/2;

}

Using shift operations can greatly improve performance, because at the bottom of the computer, bitwise manipulation is the most convenient and fastest, so it is recommended that you modify it to:

for (val = 0; val < 100000 val = 5)

{

a = Val << 3;

b = Val >> 1;

}

While the shift operation is fast, it may make the code less understandable, so it is best to add the appropriate annotation. 12. Don't keep creating object references within the loop

For example:

for (int i = 1; I <= count; i++)

{

Object obj = new Object ();

}

This can lead to the existence of Count object references in memory, which, when count is large, consumes memory, and is suggested to read:

Object obj = null;for (int i = 0; I <= count; i++) {obj = new Object ();}

In this case, there is only one object reference in memory, each time new object (), the object reference point to a different object, but only one in memory, which greatly saves memory space. 13, based on efficiency and type checking considerations, should use the array whenever possible, cannot determine the size of the array to use the ArrayList 14, try to use HashMap, ArrayList, StringBuilder, unless the thread security needs, otherwise do not recommend the use of Hashtable, Vector, StringBuffer, the latter three due to the use of synchronization mechanism resulting in performance costs 15, do not declare the array as public static final

Because it makes no sense, it just defines the reference as static final, the contents of the array can be changed at will, and declaring the array as public is a security vulnerability, which means that the array can be changed by the external class 16, try to use a single example in the appropriate situation

Using a single example can reduce the load burden, shorten the load time, increase the efficiency of loading, but not all places are applicable to the single case, in simple terms, the single case mainly applies to the following three aspects:

(1) Controlling the use of resources and controlling the concurrent access of resources through thread synchronization

(2) Control instance is produced to achieve the goal of saving resources

(3) Control the sharing of data, without establishing a direct correlation, let a number of unrelated processes or threads to achieve communication between 17, as far as possible to avoid the arbitrary use of static variables

You know, when an object is referenced by a variable that is defined as static, the GC usually does not reclaim the heap memory that the object occupies, such as:

public class A
{

private static B = new B ();

}

At this point, the life cycle of static variable B is the same as Class A, and if Class A is not unloaded, the B object referred to by reference B will reside in memory until the program terminates 18 and the session is no longer needed.

To purge sessions that are no longer active, many application servers have a default session timeout, typically 30 minutes. When an application server needs to save more sessions, if there is not enough memory, the operating system transfers some of the data to disk, and the application server may dump some inactive sessions to disk based on the MRU (most recently used) algorithm, and may even throw out an out-of-memory exception. If the session is to be dumped to disk, it must be serialized first, and in a large cluster the cost of serializing the object is expensive. 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 of the collection, such as ArrayList, should use the most common for loop rather than the Foreach loop to traverse

This is recommended by JDK to the user. The JDK API's interpretation of the Randomaccess interface is that the implementation of the Randomaccess interface is used to indicate that it supports fast random access, and that the main purpose of this interface is to allow a generic algorithm to change its behavior so that it can be applied to a random or sequential access list to provide good performance. Practical experience shows that if the class instance that implements the Randomaccess interface is randomly accessed, the use of the normal for loop efficiency will be higher than that of the Foreach loop, and conversely, if it is sequentially accessed, the use of iterator will be more efficient. You can use code similar to the following to make a judgment:

if (list instanceof randomaccess)

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

}else{iterator<?>

Iterat or = List.iterable (); while (Iterator.hasnext ()) {Iterator.next ()}

}

The underlying implementation of the Foreach loop is the iterator iterator, see Java Syntax sugar 1: variable length parameters and the Foreach Loop principle. So the second half of the sentence &rdquo; Conversely, if it is sequential access, then using iterator will be more efficient &rdquo; means that the sequential access of those class instances, using the Foreach Loop to traverse. 20. Use synchronous code block instead of synchronization method

This point in the multithreaded module of the synchronized lock method block is very clear, unless you can determine that a whole method needs to be synchronized, otherwise try to use the synchronized code block, avoid the need for synchronization of those code is also synchronized, affecting the efficiency of code execution. 21. Declare the constants as static final and name them in uppercase

This allows the content to be placed in a constant pool during compilation, avoiding the calculation of the value of the generated constant during run time. In addition, the name of a constant in uppercase can also be convenient to distinguish between constants and variable 22, do not create some unused objects, do not import some unused classes

It doesn't make sense if the code appears in the &rdquo; The value of the local variable I am not used&rdquo;, &rdquo; The import java.util is never used&rdquo, then remove these useless content 23, avoid using reflection during program Operation

about, see reflection. Reflection is Java to provide users with a very powerful function, powerful often means that the efficiency is not high. It is not recommended that you use the Invoke method especially the frequent use of reflection mechanisms, especially methods, when you are running your program, and if it is necessary, a recommended practice is to have classes that need to be loaded by reflection to instantiate an object and put it into memory at the time of project startup &mdash; -Users are only interested in getting the quickest response speed when interacting with the end, and do not care how long it takes to start the project on the end. 24. Use database connection pool and thread pool

Both pools are used to reuse objects that avoid frequent open and close connections, which avoids the frequent creation and destruction of thread 25, IO with buffered input and output streams

Buffered input and output streams, that is, BufferedReader, BufferedWriter, Bufferedinputstream, Bufferedoutputstream, which can greatly improve IO efficiency 26, Sequential insert and random access more scenes use ArrayList, element deletion and middle insert more scenes using LinkedList

This, understand the ArrayList and LinkedList principle to know 27, do not let the public method has too many formal parameters

The public method is the externally provided method, which has two disadvantages if you give too many formal parameters to these methods:

1, violates the object-oriented programming idea, the Java emphasizes all is the object, too many formal parameters, and the object-oriented programming thought does not agree with

2, too many parameters are bound to cause the method call error probability increased

As for this &rdquo; too much &rdquo; refers to how many, 3, 4 bar. 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, as the insert method of the formal parameter 28, String constants and string constants equals when you write a string constant in the front

This is a more common trick if you have the following code:

String str = "123";
if (Str.equals ("123")) {

...

}

Recommended modifications to:

String str = "123";
if ("123". Equals (str))

{

...

}

The main thing is to avoid the null pointer exception 29, please know that in Java if (i = = 1) and if (1 = = i) is no difference, but from the reading habits, recommend the use of the former

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.