Four or five Java performance usage

Source: Internet
Author: User

Http://www.blogjava.net/wang9354/archive/2009/02/17/255190.html

1. Loop
■ In an important loop, the method call is eliminated when the loop is terminated...
For example

For (INT I = 0; I <collection. Size (); I ++ ){
  1. ...
  2. }
for(int i=0; i<collection.size();i++){...}

 

Replace...

  1. For (INT I = 0; n = collection. Size (); I <n; I ++ ){
  2. ...
  3. }
for(int i=0; n=collection.size();i<n;i++){...}

 

■ Usually, move irrelevant to the cyclic Index out of the loop

 
  1. For (INT I = 0; terminal = x. length; I <terminal; I ++ ){
  2. X [I] = x [I]/scalea * scaleb;
  3. }
 for(int i=0; terminal=x.length;i<terminal;i++){x[i] = x[i]/scaleA *scaleB;}

 

It should be:

 
  1. Double scale = scaleb * scalea;
  2. For (INT I = 0; terminal = x. length; I <terminal; I ++ ){
  3. X [I] = x [I]/scale;
  4. }
Double scale =  scaleB*scaleA;for(int i=0; terminal=x.length;i<terminal;i++){x[i] = x[i]/scale ;}

 

2. String
■ Eliminate string connections
■ When creating a long string, stringbuffter is always used to replace string
■ Pre-allocated stringbuffer space stringbuffer sb = new stringbuffer (5000 );

3. Basic Data Types
■ Use basic data types in important cycles (INT data is usually faster than long/double data)
■ The packaging class of the basic data type (Boolean, integer, etc) is mainly used when the passed method parameter must be an object reference (rather than a basic data type)
■ Use the static final modifier for all constant algebra expressions
■ Make constants easier to reference (the compiler computes constant expressions in advance)

 

4. Exceptions
■ Exceptions are only used when an exception is thrown by a single true error condition, such as the novel 520 www.5a5w.cn.
It takes a lot of time to throw an exception and execute a catch code block (mainly because a snapshot of the thread stack is required when an exception is created)
An exception is thrown only when the condition is abnormal.

■ To throw an exception, you must first create a new object.

The constructor of the throwable interface calls the local (native) method named fillinstacktrace (), the fillinstacktrace () method checks the stack, and collects Call trace information.

As long as an exception is thrown, the VM must adjust the call stack because a new object is created during processing.

Exceptions can only be used for error handling and should not be used to control program processes.
■ Optimize the compiler and runtime. put several methods in a try/Catch Block instead of implementing several try/catch blocks for each method call.

 
  1. Try {
  2. Some. Method1 (); // difficut for java1.4
  3. } Catch (method1exception e ){
  4. Handle exception 1 // to optimize this code
  5. }
  6. Try {
  7. Some. method2 (); // difficut for java1.4
  8. } Catch (method2exception e ){
  9. Handle exception 2 // to optimize this code
  10. }
  11. Try {
  12. Some. method3 (); // difficut for java1.4
  13. } Catch (method3exception e ){
  14. Handle exception 3 // to optimize this code
  15. }
try{Some.method1();   //Difficut for java1.4}catch(method1Exception e){handle exception 1  // to optimize this code}try{Some.method2();   //Difficut for java1.4}catch(method2Exception e){handle exception 2  // to optimize this code}try{Some.method3();   //Difficut for java1.4}catch(method3Exception e){handle exception 3  // to optimize this code}

 

It should be written as follows:

 
  1. Try {
  2. Some. Method1 ();
  3. Some. method2 ();
  4. Some. method3 (); // difficut for java1.4
  5. } Catch (method1exception e ){
  6. Handle exception 1
  7. } Catch (method2exception e ){
  8. Handle exception 2
  9. } Catch (method3exception e ){
  10. Handle exception 3
  11. }
try{Some.method1();Some.method2();Some.method3();   //Difficut for java1.4}catch(method1Exception e){handle exception 1}catch(method2Exception e){handle exception 2}catch(method3Exception e){handle exception 3}

 

5. Benchmark

■ Note that all these techniques may vary with platforms and virtual machines.
For example, in some servlet containers, using an outputstream as a byte output will be faster.
1. In other containers, a printwriter can output characters faster.
■ These techniques describe the most portable suggestions
■ You may need to run some benchmarks to determine what is the fastest on your platform.

 

6. Create a class instance without the New Keyword

■ When the new keyword is used to create an instance of the class, all constructors in the constructor chain are automatically called.

But if an object implements the cloneable interface, we can call its clone () method. The clone () method does not call any class constructor.

When using design pattern, it is very easy to use the clone () method to create a new object instance if you create an object in factory mode.

For example, the following is a typical Implementation of the factory mode:

 
  1. Public static credit getnewcredit (){
  2. Return new credit ();
  3. }
public static Credit getNewCredit() {return new Credit();} 

After optimization:

 
  1. Private Static credit basecredit = new credit ();
  2. Public static credit getnewcredit (){
  3. Return (credit) basecredit. Clone ();
  4. }
private static Credit BaseCredit = new Credit();public static Credit getNewCredit() {return (Credit) BaseCredit.clone();} 

The above idea is also useful for Array Processing.

7. Use non-blocking I/O 

JavaEarlier JDK versions do not support non-blocking I/O APIs. To avoid I/O congestion, some applications use the method of creating a large number of threads (in good cases, a buffer pool is used ). This technology can be seen in many applications that must support concurrent I/O streams, such as web servers, quote and auction applications. However, creating a Java thread requires considerable overhead.

JDK 1.4 introduces a non-blocking I/O Library (Java. NiO ). If an application requires JDK of an earlier version, there is a software package that supports non-blocking I/O.

 

8. Do not reinitialize variables. 

■ By default, Java initializes the variable to a definite value when calling the class constructor: all objects are set to null, set integer variables (byte, short, Int, long) to 0, float and double variables to 0.0, and logical values to false.

This is especially important when a class is derived from another class, because when an object is created using the new keyword, all constructors in the constructor chain are automatically called.

 

9. Specify the final modifier of the class as much as possible. 

■ Classes with final modifiers cannot be derived. There are many examples of final applications in the Java core API, 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 as final, all the methods of this class are final. The Java compiler will look for opportunities to inline (Inline) All final methods (this is related to the specific compiler implementation ). This can increase the performance by an average of 50%.

 

10. Use local variables whenever possible 

■ Parameters passed during method call and 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. In addition, local variables may be further optimized depending on the specific compiler/JVM. See use stack variables whenever possible.

 

11. multiplication and division 

■ Consider the following code:

 
  1. For (val = 0; Val <100000; Val + = 5) {alterx = Val * 8; myresult = Val * 2 ;}
for (val = 0; val < 100000; val +=5) { alterX = val * 8; myResult = val * 2; } 

After optimization:

 
  1. For (val = 0; Val <100000; Val + = 5) {alterx = Val <3; myresult = Val <1 ;}
for (val = 0; val < 100000; val += 5) { alterX = val << 3; myResult = val << 1; } 

 

The modified code does not multiply by 8. Instead, it uses the equivalent three-bit left shift operation, and one-bit left shift operation is equivalent to multiplying 2. Correspondingly, the one-bit operation on the right 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 understand, so it is best to add some comments.

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.