Java----Code Optimization Chapter

Source: Internet
Author: User

First, the reason why we do this:

1. Efficiency (most important)

2. Readability, easy to post maintenance. (also very important)

Second, the Code optimization requirements:

1. Reduce the volume of the code.

2. Improve the operation efficiency of the code.

Third, the optimization of common code:

  1. Reuse objects as much as possible :

In particular, the reuse of string objects. The most common is the concatenation of strings:

When you encounter frequent wipe stitching string. Remember, you must use Stringbuilder/stringbuffer.

For example:

1     arraylist<string> list; 2     //omitted list initialization.  3     new  StringBuilder (); 4     5      for (String s:list) {6        builder.append (s); 7     }8     String result = builder.tostring ();

Cause: Not only does the Java virtual machine take time to generate objects, but it also takes time to process and reclaim objects, and generating too many objects is bound to affect program performance.


2. Use local variables whenever possible:

Local variables are created in the stack, created quickly, and disappear automatically without the need for additional garbage collection.

Static variables, instance variables, etc. are created in the heap and are slow to create, and are also dependent on the Java garbage collection mechanism for processing.

  

  3. Close the flow in a timely manner:

In Java program Development, after the I/O, database operation is finished, be sure to remember to close the stream.

Cause: Not shutting down the stream can be costly to the system and can even have serious consequences for the data.

4. Use lazy Loading

Lazy Loading: The object is created when it is used.

For example:

1     String prefix = "Gebi"; 2     3     if ("Laowang". Equals (name)) {4         list.add (prefix + name); 5     }

To be replaced by:

1     if ("Laowang". Equals (name)) {2         String prefix = "Gebi"; 3         List.add (prefix + name); 4     }

5. Avoid using Try...catch in loops, use try...catch in the outer loop

  

6.try...catch not too big.

Do not put the useless code, that is, the code that does not throw the exception into the Try...catch block, reducing the size of the Try...catch code block.

Ensure code readability, ease of maintenance, robustness.

  

  7. Avoid creating references to objects within the loop as much as possible.

Especially when the circulation volume is large.

1      while (i<1000) {2         New Object (); 3     }

Suggested changes to:

1     NULL ; 2             3      while (i<1000) {4         New Object ();

Each time new object () is used, the object reference points to the object.

When the number of loops is high, such as the first, the JVM creates a reference to 1000 objects, and the second memory has only one copy of the object reference. This greatly saves memory space.

  8. Do not use static variables arbitrarily.

When an object is referenced by a variable declared as static, the Java garbage collector does not clean up the heap memory that the object occupies.

The heap memory occupied by a static variable is not released until the end of the program in which the variable is located. That is, the static variable life cycle = Class life cycle.

  9. Do not create some unused objects, do not import some unused classes.

  10. Using buffered I/O streams:

Buffered I/O streams can greatly improve I/O efficiency. BufferedWriter, BufferedReader, Bufferedinputstream, Bufferedoutputstream.

  11. Wrapper class data converted to string use: toString

    Integer i = 1;

Wrapper class data conversion to string method speed ranking:

i.ToString > string.valueof (i) > "" + I

  

 12.MAP traversal efficiency: entryset > KeySet

1     //EntrySet ()2      for(Entry<string, string>Entry:map.entrySet ()) {3String key =Entry.getkey ();4String value =Entry.getvalue ();5SYSTEM.OUT.PRINTLN (key + ":" +value);6     }7     8     //Upper and lower contrast9     Ten     //KeySet () One      for(String key:map.keySet ()) { AString value =Map.get (key); -SYSTEM.OUT.PRINTLN (key + ":" +value); -}

  

13. A collection of iterator and foreach () traversal.

In the introduction of the algorithm, the algorithm is designed to improve space efficiency and time efficiency. But often time and space cannot coexist.

Time efficiency: Iterator > ForEach ()

Code readability: ForEach () > Iterator

1 //Iterator2set<entry<string, string>> entryset =Map.entryset ();3Iterator<entry<string, string>> iter =entryset.iterator ();4      5      while(Iter.hasnext ()) {6entry<string, string> Entry =Iter.next ();7String key =Entry.getkey ();8String value =Entry.getvalue ();9SYSTEM.OUT.PRINTLN (key + ":" +value);Ten}

Contrast:

1     // ForEach () 2      for (entry<string, string> entry:map.entrySet ()) {3         String key = Entry.getkey (); 4         String value = entry.getvalue (); 5         SYSTEM.OUT.PRINTLN (key + ":" + value); 6     }

Personally, it is recommended that you use iterator to iterate through the collection when working with big data.

But with small data, you use foreach () for readability and post-maintenance.

Both should be mastered in combination with each other.

Java----Code Optimization Chapter

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.