Java Development Attention Optimization

Source: Internet
Author: User
Tags error handling exception handling garbage collection int size sessions
3. Initialize an instance less with new:Use new to initialize an instance of a class as little as possible, when an object is initialized with new, all constructors of its constructor chain are called, so the new operator consumes the system resources, and the new object takes more time than the local variable assignment. Also, when objects are generated, the system takes time for garbage collection and processing.

When new creates an object that is unavoidable, be careful to avoid using new to initialize an object multiple times.

Try to create the object when you use it. Such as:

NewObject object = new NewObject ();
int value;
if (i>
0)
{
 
value =object.getvalue ();
}

  the preceding code can be modified to:

int value;
if (i>
0)
{
NewObject object = new NewObject ();
 
Value =object.getvalue ();
}

In addition, you should try to reuse an object instead of declaring a new homogeneous object. One way to reuse an object is to change the value of the object, such as by changing the object's variables in such a way as setvalue to achieve reuse. O 4. Select the appropriate method call: the code above should be written as:

int i = 0;
...

if (i ==0) {
 
Callmethod (i);
}

without affecting the readability and so on, several small methods can be synthesized into a large method.

in addition, adding the Final,private keyword before the method is beneficial to compiler optimization. O 5. Exception Handling Skills:Exceptions are a Java error-handling mechanism that is useful for programs, but the exception is bad for performance. Throw an exception to create a new object first, and related processing, resulting in the overhead of the system, so the exception should be used in the case of error handling, should not be used to control the process, the process as far as possible with while, if and other processing.

It is possible to synthesize a few try/catch blocks without affecting the robustness of the code.
O 6. Use local variables and static variables as much as possible:Use local variables as much as possible, and the parameters passed when the method is invoked and the temporary variables created in the call are saved in the stack (stack) faster. Other variables, such as static variables, instance variables, and so on, are created in the heap (Heap) in a slower speed.

Try to use a static variable, the modifier static, if the variable in the class does not change with his instance, it can be defined as a static variable, so that all of his instances share the variable.     O 7. Synchronous Processing Skills:Synchronization is mainly in the case of multithreading, for multithreading at the same time to provide object data security mechanism, multithreading is a more complex topic, the application of multithreading is to obtain performance improvements, should minimize synchronization.

In addition, if you need to sync, you can reduce the synchronized code snippet, such as synchronizing only a method or function, not the entire code.
O 8. Use the API provided by Java itself as much as possible:Java APIs generally do the performance considerations, if the same function, the use of the API rather than write their own code, such as the common code for the group to copy:

int size = 1000;
string[] StrArray1 = new String[size];
string[] strArray2 = new String[size];
For (Inti=0;i the size;i++) { // Assigning values
  StrArray1 = (New String ("Array:" + i));
}

For (Inti=0;i the size;i++) { // Copy
  strarray2= (New String ((String) a));
}
The above code, if you are using Java-provided APIs, can improve performance:

int size = 1000;
string[] StrArray1 = new String[size];
string[] StrArray2 = new String[size];
for (inti=0;i<size;i++) {//Assignment
StrArray1 = (New String ("Array:" + i));
}

System.arraycopy (strarray1,0,strarray2,0,size); Copy

The same rule is that system.arraycopy () should be used when there is a large amount of data to replicate. O 9. Minimize I/O operations:Input/output (I/O) includes many aspects, we know, the I/O operation is very consuming system resources. I/O operations should be used sparingly in the program. When used, you can note:. The rational control of output function System.out.println () is useful for most of the time, especially when the system is debugged, but it also produces a lot of information appearing in the console and log, while the output has the process of serialization and synchronization, resulting in overhead.

Especially in the release, to reasonable control output, can be in the project development, design a debug tool class, in this class can realize output switch, output level, according to different conditions for different output control.
O 10. Use caching as much as possible:O 12. Try not to use synchronization:The Servlet is a potential. O 13. Do not need to keep too much information in HttpSession in

Many times, it is necessary to store some objects in HttpSession, can speed up the development of the system, such as the online store system will store the shopping cart information in the user's session, but when the storage of large amounts of information or large objects in the conversation, is harmful, especially when the user's access to the system is very Large, the need for memory will be very high.

In concrete development, there should be a trade-off between the two.
is multi-threaded to handle different requests, based on the previous synchronization of the analysis, if there are too many synchronization will lose the advantages of multithreading O 14. Clear session:O 16. Caching the Home interface:The EJB library uses the Enterprise Bean's client to create its instance through its home interface. The client can access it through JNDI. The server is retrieved by the Lookup method.

JNDI is a remote object that is invoked through RMI and is often more time-consuming to access. So, at design time, you can design a class that is designed to cache the home interface, get the required home interface when the system is initialized, and cache it, as long as the reference is cached.
Typically, when a set timeout is reached and some sessions are inactive, the server releases these inactive sessions. However, in this case, especially when multi-user visit, the system memory to maintain a number of invalid sessions.

When the user exits, should manually release, recycle resources, implemented as follows: ...

HttpSession thesession = Request.getsession ();
Get current session
if (thesession!= null) {
Thesession.invalidate (); Make this session invalid
}
。 Read-write memory is much faster than reading and writing to files on your hard disk, and you should use buffering whenever possible to read data directly from memory.

Use a class with buffer as much as possible instead of a class without buffer, such as using BufferedReader instead of reader, and BufferedWriter instead of writer for processing I/O operations.

You can also use Bufferedinputstream instead of InputStream to get better performance. In Java, everything is an object, and if a method is invoked, the processor first checks to see which object the method belongs to, whether the object is valid, what type of object it belongs to, and then select the appropriate method and invoke it.

You can reduce the invocation of a method by the same method:

Public void Callmethod (int i) {
  if (i ==0) {
   return ;
  }
  ... // Other processing
}

if called directly,

int i = 0;
...
Callmethod (i);
  then look at the following code slice: ..

for (int i = 0;i the 100000;i++)
if (i%10 = = 9) {
 

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.