Performance Optimization Techniques for "quick" J2EE programs in detail

Source: Internet
Author: User

The performance of the system developed on the application J2EE platform is a concern of both system users and developers. This article discusses the impact of code on the performance from several aspects that should be paid attention to during Server programming, and summarize some suggestions.

Key words: Performance Java J2EE EJB Servlet JDBC

  I. Summary

Java 2 Platform and Enterprise Edition (J2EE) are the development platforms currently used by many commercial application systems, this technology provides a component-based method to design, develop, assemble, and deploy enterprise-level applications. The J2EE platform provides a multi-layer Distributed Application Model for faster development and release of new application solutions.
J2EE is a technical specification that defines the entire standard application development architecture and a deployment environment. When developing an application developer, they only need to focus on the implementation of specific business logic and business rules, other system development problems such as transactions, persistence, and security can be handled by application containers or servers. After the development is completed, the system can be conveniently deployed to the application server that implements the specifications.

As a commercial application system on the network, there are a large number of users simultaneously accessing it, there is a conflict between excessive resource requests and limited server resources (memory, CPU time, network bandwidth, etc.), and the performance of the application system becomes very important, sometimes the correct code does not guarantee the project's success. performance is often the final key to determining whether a project is successful.

This article mainly discusses Code Performance Optimization and improvement from the perspective of performance.

  2. Common Java programming

The basis of J2EE is Java. The impact of common Java code problems on the Performance of application systems is discussed below.

· Use StringBuffer instead of String

When processing string addition, the common syntax is :..

String str1 = "Hello ";
String str2 = "welcome to world ";
String str3 = str1 + "," + str2 + "! ";
System. out. println (str3 );

Many people know that such code is very inefficient, because String is used to store String constants. If you want to execute the "+" operation, the system will generate some temporary objects, and manage these objects, causing unnecessary overhead.

If a string has a connected operation, the alternative method is to use the append method of the StringBuffer class. Its default constructor and append implementation are:

Public StringBuffer () {// Constructor
This (16); // default capacity 16}

Public synchronized StringBuffer append (String str ){
If (str = null ){
Str = String. valueOf (str );
}

Int len = str. length ();
Int newcount = count + len;
If (newcount> value. length)

ExpandCapacity (newcount );

// Expand capacity
Str. getChars (0, len, value, count );
Count = newcount;
Return this;
}

When the size of a string exceeds 16 by default, the Code expands the capacity. To avoid the re-expansion of the object capacity, the better syntax is:

StringBuffer buffer = new StringBuffer (30 );
// Allocate the specified size.
Buffer. append ("hello ");
Buffer. append (",");
Buffer. append ("welcometo world! ");
String str = buffer. toString ();

· Allocate reasonable space and size when generating objects

Many classes in Java have their default space allocation size. For initialization of some objects with size, we should estimate the object size and then use it for initialization, the above example also illustrates this problem. When StringBuffer is created, we specify its size.

Another example is Vector. When Vector vect = new Vector () is declared, the system calls:

Public Vector () {// default constructor
This (10); // The capacity is 10;
}

By default, 10 objects are allocated. When the add method is executed, you can see the specific implementation is :..

Public synchronized boolean add (Object o ){
ModCount ++;
EnsureCapacityHelper (elementCount + 1 );
ElementData [elementCount ++] = o;

Return true;
}

Private void ensureCapacityHelper (int minCapacity ){
Int oldCapacity = elementData. length;
If (minCapacity> oldCapacity ){
Object oldData [] = elementData;
Int newCapacity = (capacityIncrement> 0 )? (OldCapacity + capacityIncrement ):
(OldCapacity * 2 );
If (newCapacity <minCapacity ){
NewCapacity = minCapacity;
}
ElementData = new Object [newCapacity];
System. arraycopy (oldData, 0, elementData, 0, elementCount );
}
}

We can see that when the Vector size exceeds the original size, some code aims to expand the capacity. If we know the size of the Vector in advance, we can specify its size, avoid the overhead of capacity expansion. If we know that the Vector size is 100, Initialization is like this.

Vector vect =... new Vector (100 );

· Optimized the loop body

Loop is a relatively repetitive place. If the number of loops is large, the impact of bad code in the loop body on efficiency will be magnified and highlighted. Consider the following code :..

Vector vect = new Vector (1000 );
...
For (inti = 0; I ...
}

The for loop part is rewritten:

Int size = vect. size ();
For (int I = 0; I> size; I ++ ){
...
}

If the size is 1000, the system call overhead of the size () can be reduced by 1000 times, avoiding the loop weight of the system.

Let's look at the following code :..

For (int I = 0; I <100000; I ++)
If (I % 10 = 9 ){
... // Execute once every 10 times
}

Rewriting can also improve efficiency :..

For (inti = 0, j = 10; I <100000; I ++, j --){
If (j = 0 ){
... // Execute once every 10 times
J = 10;
}
}

Therefore, when there is a large loop, check whether the efficiency in the loop is not high and find a better solution for improvement.

· Object Creation

Try to use new to initialize an instance of a class. when an object is initialized with new, all constructors of its constructor chain are called, therefore, the new operator consumes a lot of system resources. the time consumed by a new object is often thousands of times the time consumed by the assignment of local variables. At the same time, after the object is generated, the system will take time to recycle and process the garbage.

When creating a new object, do not use new to initialize an object multiple times.

Try to create this object again when using it. For example:

NewObject object = new NewObject ();
Int value;
If (I> 0)
{
Value = object. getValue ();
}

It can be changed:

Int value;
If (I> 0)
{
NewObject object = new NewObject ();
Value = object. getValue ();
}

In addition, we should try to reuse an object instead of declaring a new similar object. A Method to reuse an object is to change the value of the object. For example, you can use setValue or another method to change the variable of the object for reuse.

· Considerations for variables

Use local variables whenever possible. The parameters passed during method calling and the temporary variables created in the call are saved in the Stack, which is faster. Other variables, such as static variables and instance variables, are created in Heap, which is slow.

Use static variables as much as possible, that is, the modifier static. If the variables in the class do not change with other instances, they can be defined as static variables, so that all of his instances share the variable.

· Method call

In Java, everything is an object. If a Method is called, the processor must first check which object the Method belongs to, whether the object is valid, and what type the object belongs, then select the appropriate method and call it.

This can reduce the call of methods. The same method: <

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.