Java code optimization

Source: Internet
Author: User
Tags try catch

I have sorted out some code and optimization methods that affect performance, and hope to supplement and optimize them in the future.

1. How to use exception
Exception reduces performance. To throw an exception, you must first create a new object. The constructor in the throwable interface calls the local method named fillinstacktrace. This method is responsible for the entire framework of the inspection stack to collect tracking information. In this way, whenever an exception is thrown, it requires the virtual machine to load the call stack because a new object is created in the middle.
An exception should only be used when an error occurs, rather than a control flow.
2. Do not initialize the variable twice.
Java initializes a variable to a known value by default by calling a unique class constructor. All objects are set to null, integers (byte, short, Int, long) to 0, float and double to 0.0, and Boolean to false. This is especially important for classes that are extended from other classes. This is the same as when a new keyword is used to create an object, all a series of constructors are automatically called.
3. Set the class to final wherever possible
Classes marked as final cannot be extended. There are a lot of examples of this technology in core Java API, such as Java. Lang. String. Marking the string class as final prevents developers from creating their own length methods.
For more details, if the class is final, the methods of all classes are also final. The Java compiler may link all the methods (depending on the implementation of the compiler ). In my tests, I have seen an average performance increase of 50%.
4. Use local variables wherever possible
The independent variables that belong to the method call part and the temporary variables that declare this part of the call are stored in the stack, which is faster. Such as static, instance variables and new objects are created in the heap, which is slow. More in-depth Optimization of local variables depends on the compiler or virtual machine you are using.
5. Stop smart
Many developers write reusable and flexible code in their minds, and sometimes they produce additional overhead in their programs. Once or in other times they wrote code similar to this:
Public void dosomething (File file ){
Fileinputstream filein = new fileinputstream (File );
// Do something
He is flexible enough, but they also produce more expenses. The thing behind this idea is to manipulate an inputstream instead of a file, so it should be rewritten as follows:
Public void dosomething (inputstream ){
// Do something
6. multiplication and division
I have too many things that apply to Moore's law-it states that the CPU power doubles every year. Moore's law shows that the number of bad code written by developers three times a year has increased, removing any benefit of Moore's Law.
Consider the following code:
For (val = 0; Val & lt; 100000; Val + = 5) {shiftx = Val 8; myraise = Val 2 ;}
If we use a bit, the performance will increase by six times. Here is the rewritten code:
For (val = 0; Val & lt; 100000; Val + = 5) {shiftx = Val & lt; 3; myraise = Val & lt; 1 ;}
Instead of multiplying 8, we use three shifts to the left with the same effect. Every movement is multiplied by 2, and the variable myraise proves this. The shift to the right is equal to dividing by 2. Of course, this will speed up the execution, but it may make your stuff hard to understand. So this is just a suggestion.
7. Use code to effectively handle memory overflow
Outofmemoryerror is a common problem that occurs when the memory is insufficient. The following code can effectively identify memory overflow errors and effectively recycle the memory when memory overflow occurs.
This method is equivalent to effective management of connection pool overflow.
Import java. util .*;
Public class dataserver
{

Private hashtable DATA = new hashtable ();
Public object get (string key)
{

Object OBJ = data. Get (key );
If (OBJ = NULL)
{

System. Out. Print (Key + "");
Try
{

// Simulate getting lots of data
OBJ = new double [1000000];
Data. Put (Key, OBJ );
}

Catch (outofmemoryerror E)
{

System. Out. Print ("/no memory! ");
Flushcache ();
OBJ = get (key); // try again
}

}
Return (OBJ );
}

Public void flushcache ()
{

System. Out. println ("Clearing cache ");
Data. Clear ();
}

Public static void main (string [] ARGs)
{

Dataserver DS = new dataserver ();
Int COUNT = 0;
While (true) // infinite loop for test
DS. Get ("" count + );
}

}
8. Lazy loading (lazy evaluation) is loaded only when it needs to be loaded.
Static public long
Factorial (int n) throws illegalargumentexception
{

Illegalargumentexception =
New illegalargumentexception ("must be & gt; = 0 ");
If (N & lt; 0 ){
Throw illegalargumentexception;
} Else if (n 0) | (N 1 )){
Return (1 );
} Else (
Return (N * factorial (n-1 ));
}

Optimized Code
Static public long
Factorial (int n) throws illegalargumentexception
{

If (N & lt; 0 ){
Throw new illegalargumentexception ("must be & gt; = 0 ");
} Else if (n 0) | (N 1 )){
Return (1 );
} Else (
Return (N * factorial (n-1 ));
}

9. An exception is thrown at the place where it needs to be thrown. Try catch can be integrated for integration.
Try {
Some. Method1 (); // difficult for javac
} Catch (method1exception e) {// and the JVM Runtime
// Handle exception 1 // to optimize this
} // Code
Try {
Some. method2 ();
} Catch (method2exception e ){
// Handle exception 2
}

Try {
Some. method3 ();
} Catch (method3exception e ){
// Handle exception 3
}

The code below is more easily optimized by the compiler
Try {
Some. Method1 (); // easier to optimize
Some. method2 ();
Some. method3 ();
} Catch (method1exception e ){
// Handle exception 1
} Catch (method2exception e ){
// Handle exception 2
} Catch (method3exception e ){
// Handle exception 3
}

10. Optimization of the For Loop
Replace...
For (INT I = 0; I & lt; collection. Size (); I ++ ){
...
}

With...
For (INT I = 0, n = collection. Size (); I & lt; n; I ++ ){
...
}

11. String operation optimization
When performing the + operation on strings, it is best to use a statement
// Your source code looks like...
String STR = "Profit = revenue (" Revenue
"-Cost (" cost "";

// Compilation Method
String STR = new stringbuffer (). append ("Profit = revenue (").
Append (revenue). append ("-cost (").
Append (COST). append (""). tostring ();
Use the stringbuffer. append () method to perform string operations in a loop.
String sentence = "";
For (INT I = 0; I & lt; wordarray. length; I ++ ){
Sentence + = wordarray [I];
}

Optimized
Stringbuffer buffer = new stringbuffer (500 );
For (INT I = 0; I & lt; wordarray. length; I ++ ){
Buffer. append (wordarray [I]);
}

String sentence = buffer. tostring ();
12. Object reuse (especially for large objects)
Public
Class Point
{

Public int X;
Public int y;
Public point ()
{

This (0, 0 );
}

}
Optimized:
Public Class component
{

Private int X;
Private int y;
Public point getposition ()
{

Point Rv = new point (); // create a new point
RV. x = x; // update its state
RV. Y = y;
Return RV;
}

}
// Process an array of component positions...
For (INT I = 0; I & lt; componentarray. length; I ++ ){
Point Position = componentarray [I]. getposition ();
// Process position value...
// Note: A point object is created for each iteration
// Of the loop...
}

Optimization can be performed again. Only one class object is used :)
Public
Class component
{

Private int X;
Private int y;
Public point getposition (point RV)
{

If (Rv = NULL) Rv = new point ();
RV. x = x; // update its state
RV. Y = y;
Return RV;
}

// Create a single point object and reuse it...
Point P = new point ();
For (INT I = 0; I & lt; componentarray. length; I ++ ){
Point Position = componentarray [I]. getposition (P );
// Process position value...
// Note: Only one point object is ever created.
}

13. J2EE-related
A) Try not to put large objects in httpsession or other objects to be serialized, and pay attention to clearing the session in time.
B) Use the precompiled statement preparestatement instead of createstatement.
C) try to use the connection pool
D) You can use the cache when you can use it. For details, see jive (Cache/cacheable/cacheobject/cachesizes/defaultcache/linkdlist/linkdlistnode) or OFBiz (Org. OFBiz. core. util. utilcache. java)

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.