Java Code optimization Programming

Source: Internet
Author: User
Tags modifier stringbuffer

resources available for the program to use (memory, CPU time, network bandwidth, etc.) is limited, the purpose of optimization is to allow the program to use as

Less resources to complete the scheduled tasks. Optimization usually consists of two parts: reducing the volume of the Code and improving the efficiency of the Code.

The main discussion in this paper is how to improve the efficiency of code.
in Java programs, most of the reasons for performance problems lie not in the Java language, but in the program itself. Develop a good code compilation

writing habits are important, such as using the java.lang.String and Java.util.Vector classes correctly and skillfully, which can

Significantly improve the performance of the program. Let's take a concrete look at the problem in this area.

1. It is not possible to derive a class that specifies the final modifier of the class with the final modifier. In the Java Core API, there are many applications

Final examples, such as java.lang.String. Specifying final for the string class prevents people from overwriting the length () method. Other

, if a class is specified as final, all methods of that class are final. The Java compiler will look for opportunities inline (inline

all final methods (this is related to the specific compiler implementation). This will increase the performance by an average of 50%.

2, the amount of 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, the health

An excessive number of 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 on the stack (stack)

, the speed is faster. Other variables, such as static variables, instance variables, and so on, are created in the heap and areslower. Other than that

depending on the compiler /JVM, local variables may be further optimized. See Use stack variables whenever possible.

4. Do not repeat initialization variables by default, when you call the class's constructor, Java initializes the variable to the determined value:

all objects are set to null, and integer variables (byte, short, int, long) are set to 0,float and double variables

set to 0.0, the logical value is set to False. This is especially important when a class is derived from another class, because the new

When a keyword creates an object, all constructors in the constructor chain are called automatically.

5, in Java + ORACLE's application development, Java Embedded SQL statements as far as possible to use uppercase form, in order to alleviate

The parsing burden of the Oracle parser.

6, in the Java programming process, the database connection, I/O flow operation must be careful, after the use is complete, close in time to release

Resources. Because the operation of these large objects can cause large overhead, a slight carelessness, which can lead to serious consequences.

7, because the JVM has its own GC mechanism, does not require the program developers too much to consider, to a certain extent, to alleviate the burden of developers

, but also missed the hidden dangers, excessive creation of objects will consume a large amount of memory of the system, serious will lead to memory leaks, therefore,

It is of great significance to ensure the timely recovery of outdated objects. the JVM reclaims garbage by: The object is not referenced; however, the JVM's GC

Not very witty, even if the object satisfies the garbage collection condition, it does not necessarily get recycled immediately. Therefore, we recommend that the object

When it is finished, it should be manually set to null.

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

9, minimize the repetition of the variable calculation

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 + +) {

  ...

  }

10, try to use the lazy loading strategy, that is, when needed to start the creation.

For example: String str = "AAA";

  if (i = = 1) {

  List.add (str);

  }

Should be replaced by:

  if (i = = 1) {

  String str = "AAA";

  List.add (str);

  }

11, cautious use of abnormal
exceptions are bad for performance. Throwing an exception begins with creating a new object. the constructor call for the Throwable interface is named

The local (Native) method of Fillinstacktrace (), the Fillinstacktrace () method checks the stack, collects the call trace letter

Information . Whenever an exception is thrown,the VM must adjust the call stack because a new object is created during processing. Abnormal

Can only be used for error handling and should not be used for control procedures.

12, do not use in the loop:

  Try {

  } catch () {

  }

It should be placed at the outermost layer.

13, set the initial capacity 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 pass The StringBuffer constructor is used to set its initialization capacity, which can significantly improve performance. Over here

The constructor mentioned is StringBuffer (int length), the length parameter indicates that the current stringbuffer can hold the word

The number of characters. You can also use the ensurecapacity (int minimumcapacity) method after the StringBuffer object is created

set its capacity. First, let's look at the default behavior of StringBuffer and then find a better way to improve performance.

  StringBuffer maintains an array of characters internally, when you use the default constructor to create the StringBuffer object's

because the initialization character length is not set, The capacity of the StringBuffer is initialized to 16 characters, which means that the default capacitance

The amount is 16 characters. When the stringbuffer reaches its maximum capacity, it increases its capacity to twice times the current, plus 2.

That is (the old value is +2). If you use the default value, after initialization and then append the character to the inside, you append to the 16th word

it will increase the capacity to 34 (2*16+2) and increase the capacity to 70 when appended to 34 characters.

(2*34+2). Whenever StringBuffer reaches its maximum capacity, it has to create a new array of characters and then

It's too expensive to re-copy both old and new characters . So always set a reasonable stringbuffer for the

Initializing the capacity value is not an error, which results in immediate performance gains.

  The effect of the adjustment of the StringBuffer initialization process is evident. Therefore, a suitable capacity value is used to initialize the

StringBuffer is always the best advice.

14, reasonable use of Java class Java.util.Vector.

To put it simply, a A vector is an array of java.lang.Object instances. The vector is similar to an array, and its elements

can be accessed through an integer index. However,after an object of vector type is created, the size of the object can be based on the element's

Add or remove to expand and shrink. Consider the following example of adding elements to a vector:

  Object obj = new Object ();

  Vector v = new vector (100000);

  for (int i=0;

  i<100000; i++) {v.add (0,obj);}

unless there is absolutely sufficient reason to require that new elements be inserted into the The front of the vector, otherwise the code above is bad for performance

. In the default constructor,the initial storage capacity of the vector is 10 elements, and if the new element is not able to be stored at the time of joining, the

The post-storage capacity doubles every time. vector classes, like the StringBuffer class, each time the storage capability is extended, all existing elements

are copied to the new storage space. The following code fragment is a few orders of magnitude faster than the previous example:

  Object obj = new Object ();

  Vector v = new vector (100000);

  for (int i=0; i<100000; i++) {v.add (obj);}

the same rules apply to The Remove () method of the vector class. Because the elements in the vector cannot contain "voids"

, removing any other element except the last element causes the element to move forward after the element is deleted. In other words, from

The vector removes the last element several times lower than the "overhead" of the first element.
Suppose you want to go from the previous Vector removes all elements and we can use this code:

  for (int i=0; i<100000; i++)

  {

  V.remove (0);

  }

However, the preceding code is a few orders of magnitude slower than the following code:

  for (int i=0; i<100000; i++)

  {

  V.remove (V.size ()-1);

  }

from Vector type Object v the best way to remove all elements is:

  V.removeallelements ();

Assumptions Object V of the vector type contains the string "Hello". Consider the following code, which is to be removed from this vector

"Hello" string:

  String s = "Hello";

  int i = V.indexof (s);

  if (I! =-1) v.remove (s);

The code looks like nothing wrong, but it's also bad for performance. In this code,the IndexOf () method

The order search looks for the string "Hello", and the Remove (s) method also searches the same sequence. The revised version is:

  String s = "Hello";

  int i = V.indexof (s);

  if (i! =-1) v.remove (i);

In this version, we give the exact index position of the element to be deleted directly in the Remove () method, thus avoiding the second search

Cable. A better version is:

  String s = "Hello"; V.remove (s);

Finally, let's look at a Code snippet for vector class:

  for (int i=0; I++;i < V.length)

if v contains 100,000 elements, this code fragment will call the V.size () method 100,000 times. Although the size method is a

a simple method, but it still requires the overhead of a method call, at least The JVM needs to configure it and clear the stack environment. In

here,the code inside the for loop does not modify the size of the vector type Object V in any way, so the code above is best rewritten

Into the following form:

  int size = V.size (); for (int i=0; I++;i<size) < p= "" style= "Word-wrap:break-word;" ></size) <>

While this is a simple change, it still wins performance. After all, every CPU cycle is valuable.

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

16, code refactoring: Enhance the readability of the code.

For example:

  public class Shopcart {

  Private List carts;

  ...

  public void Add (Object item) {

  if (carts = = null) {

  Carts = new ArrayList ();

  }

  Crts.add (item);

  }

  public void Remove (Object item) {

  if (carts. Contains (item)) {

  Carts.remove (item);

  }

  }

  Public List Getcarts () {

  Returns a read-only list

  return collections.unmodifiablelist (carts);

  }

  Not recommended this way

  This.getcarts (). Add (item);

  }

17. Create an instance of the class without the new keyword

When you create an instance of a class with The new keyword, all constructors in the constructor chain are automatically called. But if a pair of

like it achieved Cloneable interface, we can call its clone () method. The Clone () method does not call any class constructors

when using design mode ( Design pattern), if you create an object in Factory mode, use the clone () party instead

It is very easy to create new object instances by using the For example, here is a typical implementation of the factory pattern:

  public static Credit Getnewcredit () {

  return new credit ();

  }

The improved code uses the Clone () method, as follows:

  private static Credit Basecredit = new Credits ();

  public static Credit Getnewcredit () {

  return (Credit) Basecredit.clone ();

  }

The idea above is also useful for array processing.

18. Multiplication and division

Consider the following code:

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

  Alterx = val * 8; Myresult = val * 2;

  }

Replacing multiplication operations with shift operations can greatly improve performance. The following is the modified code:

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

  Alterx = Val << 3; Myresult = Val << 1;

  }

the modified code does not multiply by 8, but instead shifts to the equivalent left-shifted 3-bit operation, with each left shift of 1 bits equal to 2 times. Phase

On the ground, the right-shift 1-bit operation is equivalent to dividing by 2. It is worth mentioning that although the shift operation is fast, it may make the code more difficult to

Solution, so it's best to add some comments.

19. 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 until a server-side program

called Httpservletrequest.getsession (true) such a statement is created only if the JSP is not displayed so that the

with <% @page session= "false"%> to close the session, the JSP file will be automatically translated into a servlet when it is added such a

- Line Statement HttpSession session = Httpservletrequest.getsession (true); This is also implied in the JSP

The origin of the session object. Because the session consumes memory resources, if you do not intend to use the session, you should

of the The JSP to close it.

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"%>
20. JDBC and I/O

If your application needs to access a large data set, you should consider using block extraction. By default,

JDBC Extracts 32 rows of data at a time. For example, if we were to traverse a 5000-row recordset, JDBC must call the database

157 times to extract all the data. If you change the block size to 512, the number of times the database is called will be reduced to 10 times.

21. servlet and Memory usage

Many developers randomly save a lot of information to a user session. Some times, objects saved in the session are not in time

Collected 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

attributed to any specific component. If you monitor the JVM's heap space, it behaves as if the memory usage is abnormally steep and steep.

want to learn the front-end development of students, you can add group:543627393 Study Oh!

Java Code optimization Programming

Related Article

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.