Java code optimization

Source: Internet
Author: User

Optimization usually consists of two parts: reducing the volume of the Code and improving the efficiency of the Code.

1. The class that specifies the final modifier of the class with the final modifier is not derived as much as possible. In the Java Core API, there are many examples of final applications, such as java.lang.String. Specifying final for the string class prevents people from overwriting the length () method. In addition, if you specify a class to be final, all methods of that class are final. The Java compiler looks for the opportunity Inline (inline) for all final methods (this is related to the specific compiler implementation). This will increase the performance by an average of 50%.

2, try to reuse objects. In particular, when string objects are used, StringBuffer is used instead when strings are concatenated. Because the system not only takes time to generate objects, it may take time for them to be garbage collected and processed later. Therefore, generating too many objects will have a significant impact on the performance of the program.

3. Use local variables as much as possible, parameters passed when invoking a method, and temporary variables created in the call are saved in the stack, faster. Other variables, such as static variables, instance variables, and so on, are created in the heap and are slower.

4, in Java + Oracle application development, Java Embedded SQL statements as far as possible to use uppercase form, to reduce the parsing burden of Oracle Parser

5, in the Java programming process, the database connection, I/O flow operation must be careful, after use, even if closed to release resources. Because the operation of these large objects can cause large overhead, a slight carelessness, which can lead to serious consequences.

6, because the JVM has its own GC mechanism, does not require too much consideration of program developers, to a certain extent, to alleviate the burden of developers, but also missed the hidden dangers, excessive creation of objects will consume the system of large amounts of memory, serious will lead to memory leaks, it is important to ensure the timely recovery of outdated objects. The JVM recycles garbage by saying that the object is not being referenced; however, the JVM's GC is not very witty, and even if the object satisfies the garbage collection condition, it does not necessarily get reclaimed immediately. Therefore, we recommend that you manually set NULL when the object is used.

7, when using the synchronization mechanism, should try to use method synchronization instead of code block synchronization.

8, minimizing the repetition of variables

For example: for (int i = 0;i < list.size; i + +) {
...
}
Should be replaced by:
for (int i = 0,int len = list.size (); i < Len; i + +) {
...
}

9,

Try to use the lazy loading strategy to start creating when needed.
For example: String str = "AAA";
if (i = = 1) {
List.add (str);
}
Should be replaced by:
if (i = = 1) {
String str = "AAA";
List.add (str);
}

do not use in loops:

Try {
} catch () {
}
It should be placed at the outermost layer.

11, the use of StringBuffer:
StringBuffer represents a mutable, writable string.
There are three methods of construction:
StringBuffer (); 16-character space is assigned by default
StringBuffer (int size); Allocate a space of size characters
StringBuffer (String str); Allocate 16 characters +str.length () character space
You can use the StringBuffer constructor to set its initialization capacity, which can significantly improve performance. The constructor mentioned here is stringbuffer (int length), and the length parameter represents the number of characters that the current stringbuffer can hold. You can also use the ensurecapacity (int minimumcapacity) method to set its capacity after the StringBuffer object is created. First we look at the default behavior of StringBuffer and then find a better way to improve performance.

12, use the system.arraycopy () command when copying large amounts of data.

Close the useless session in the JSP page.

A common misconception is that the session is created when there is client access, but the fact is that it is not created until a statement such as Httpservletrequest.getsession (true) is called by a server-side program, and note that if the JSP does not display the use <% @page session= "false"%> the session is closed, the JSP file is automatically translated into a servlet with such a statement httpsession session = Httpservletrequest.getsession (true); This is also the origin of the hidden session object in JSP. Because the session consumes memory resources, if you do not intend to use the session, you should close it in all JSPs.
For those pages that do not need to track session state, turning off automatically created sessions can save some resources. Use the following Page directive: <%@ page session= "false"%>

, servlet and Memory usage

Many developers randomly save a lot of information to a user session. At some point, objects saved in the session are not reclaimed in a timely manner by the garbage collection mechanism. From a performance perspective, the typical symptom is that the user feels that the system is periodically slowing down, but cannot attribute the cause to any specific component. If you monitor the JVM's heap space, it behaves as if the memory usage is abnormally steep and steep.
There are two main ways to solve this type of memory problem. The first approach is to implement the Httpsessionbindinglistener interface in all beans scoped to the session. This allows the resources used by the bean to be explicitly freed as long as the Valueunbound () method is implemented. Another option is to invalidate the session as quickly as possible. Most application servers have the option to set the session deprecation interval. Alternatively, you can programmatically invoke the session's Setmaxinactiveinterval () method, which is used to set the maximum interval of time, in seconds, that the servlet container allows for client requests before the session is invalidated.

15, select the appropriate reference mechanism in a typical JSP application system, the page header, footer section is often extracted, and then as needed to introduce the page header, footer. Currently, there are two main ways to introduce external resources into JSP pages: include directives, and include actions.

Include directives: For example, <%@ include file= "copyright.html"%>. The directive introduces the specified resource at compile time. Before compiling, the page with the include directive and the specified resource are merged into a single file. The referenced external resources are determined at compile time, and the resource is more efficient than the runtime.
Include action: For example <jsp:include page= "copyright.jsp"/>. This action introduces the results generated after the specified page executes. Because it completes at run time, the control of the output results is more flexible. However, using the include action is only advantageous when the referenced content changes frequently, or if the referenced page cannot be determined until a request to the main page is not present.

16, do not declare the array as: public static final

the use of Array (array) and Arrylist

Array ([]): The most efficient, but its capacity is fixed and can not be changed dynamically;
ArrayList: Capacity can be dynamically increased, but sacrificing efficiency;

18, try to use HashMap and ArrayList, unless necessary, it is not recommended to use Hashtable and vectors, the latter due to the use of synchronization mechanism, resulting in performance overhead.

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.