Java Performance optimization: Program optimization

Source: Internet
Author: User
Tags finally block

now the computer's processing performance is getting better, plus the JDK upgrade to some code optimization, adjustments to some details at the code level may not see a noticeable improvement in performance,

But I think in the development of attention to these, more is the ability to maintain a performance-first awareness of some of the short time to knock on the students quite meaningful.

In a cyclic condition, both the cyclic body and the judging condition should avoid the use of complex expressions and reduce the repeated calculation of variables.

1. The use of complex expressions should be avoided in the loop.

In the loop, the loop condition is calculated repeatedly, and it should be avoided to put some calculations in the loop, and the program will run faster.
Like what:

for (int i=0;i<list.size (); i++) can be changed to //My Computer, test the order of magnitude in the 10^7, the speed is increased by one times.  for (int i=0,len=list.size (); i<len;i++)

Two better use of variables
1. Fair use of the final modifier

Note that FINA modifies variables or methods in different ways. Many times the use of the "static final variable" format is a good choice.
2. Avoid unnecessary creation as much as possible, while avoiding using static variables arbitrarily

GC usually does not reclaim the memory occupied by static variable objects, so use static area code reasonably.
3. Use basic data types instead of objects
In Java, a string object consists mainly of 3 parts:
The length of the char array, offset, and string.

// creates a "hello" string, and the JVM's character cache pool also caches the string; New String ("Hello")//  at this time the program, in addition to creating a string, the string object referenced by Str also contains a char[] array, the char[] array is stored in turn h,e,l,l,o

Two more efficient use of strings
1. For constant strings, replace ' stringbuffer ' with ' string ', but use StringBuilder or StringBuffer when a string object is required to do an additive operation;

In addition, Stringbuiler (single-occupancy, multi-player buffering) with relatively good performance in single-threaded or thread-safe situations.

2. Use a better way to split a string
Java Program Performance optimization shows that the split () method supports regular expressions, is powerful, but is the least efficient; Stringtokenzer performance is better than the split () method. If you can implement your own segmentation algorithm, performance can be optimized, but for readability and maintainability, you can use StringTokenizer.
Verify in the code that:

StringBuilder sb=NewStringBuilder (); for(inti=0;i<100000;i++) {sb.append (i); Sb.append (",");} String Str=sb.tostring (); Long time1=System.currenttimemillis (); String[] Split=str.split (","); Long time2=System.currenttimemillis (); System.out.println (time2-time1); Long Time3=System.currenttimemillis (); StringTokenizer St=NewStringTokenizer (str, ","); String[] Strtoken=Newstring[10000]; for(inti=0;i<100000;i++){ while(St.hasmoretokens ()) {Strtoken[i]=st.nexttoken ();}} Long Time4=System.currenttimemillis (); System.out.println (Time4-TIME2);

On their own computer split 10,000 times, stringtokenizer average speed of about 3ms (the amount, as if the difference is not small).

Third, choose reasonable data structure according to thread safety requirement
1. Single thread should try to use HashMap, ArrayList
In a single-threaded environment, try to avoid using a set of tools optimized for multithreaded environments .
For example, avoid casual use of StringBuffer and Stringbuilder,hashmap (single-threaded maps) and Hashtable (multithreaded tables).
2. Reduce the area of synchronized action

The system overhead of the synchronization method is relatively large, so try to use the Synchronized keyword where it really needs to be synchronized.

Four rational selection of Set tool class
1. Specify the initial size when using partially auto-expanding data structures such as vectors, HashTable, hashmap, etc.
Looking at the source of the vector, you will find the definition of initialcapacity, Capacityincrement, to specify the initial capacity and the auto-expansion size after the collection is filled,
Vector at initialization, the default capacity size is 10, most of the time this capacity is not enough, will be extended operations.
Like what:

 Public New

2. Try to avoid using two-dimensional arrays
Compared to a one-dimensional array, the two-dimensional array is less efficient and can achieve 10 times times the difference. Some of the data structures or algorithm topics that you've done before,

For example , a one-dimensional array instead of a two-dimensional array represents a coordinate system, since space-time expenditures can be used to represent the horizontal and vertical coordinates using subscripts and values .
3. Use System.arraycopy () instead of passing to iterate over the array


Note in the five-statement control structure
The final keyword is used in 1.java to indicate that a function is an inline function, and the final keyword tells the compiler to consider performance improvements at compile time
An inline function is when a program compiles a call expression for an inline function that appears in a program that is replaced directly by the function body of the inline function. Understanding inline functions can be analogous to C-language macro definitions.

This blog post tests the use of final optimizations. http://blog.csdn.net/inkfish/article/details/4849028

2. In operations such as file read and write, access to links, related resources can be released in the finally block

Six mathematical calculations for lifting performance
1. As with the C language, the multiplication method should use displacement if possible.

Usually if you need to multiply or divide by 2 n times, you can use the Shift method instead,

In Java are left-shifted, signed right-shifted, and unsigned right-shift operators. The shift operator operates on an int value only, and if it is not int, the compiler will make an error.

a=a*4; b=B/4//a=a<<2; b=b>>2//  //////except 8 = Shift right 3 bit by 8 = shift Left 3 bit 

Java Performance optimization: Program optimization

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.