Java ---- code optimization, java ---- code

Source: Internet
Author: User

Java ---- code optimization, java ---- code

1. The purpose of doing so:

1. Efficiency (most important)

2. readability for later maintenance. (Also important)

 

Ii. code optimization requirements:

1. reduce the size of the Code.

2. Improve code running efficiency.

 

Iii. Optimization of Common Code:

  1. Try to reuse objects:

In particular, the reuse of String objects. The most commonly used is String concatenation:

When the String is frequently rubbed and spliced. Remember to use StringBuilder/StringBuffer

For example:

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

Cause: the Java Virtual Machine takes not only time to generate objects, but also time to process and recycle objects. generating too many objects will inevitably affect program performance.


2. Use local variables as much as possible:

The local variables are created in the stack. The creation speed is fast. Once used up, the local variables automatically disappear without additional garbage collection.

Static variables and instance variables are created in the heap, which is slow and dependent on the Java garbage collection mechanism.

  

  3. Close the stream in time:

In Java program development, after I/O and database operations are completed, you must remember to close the stream.

Cause: If the stream is not closed, it will cause a lot of overhead to the system, and even cause serious consequences to the data.

4. Use lazy loading

Lazy loading: This object is created only when it is used.

For example:

1     String prefix = "gebi";2     3     if ("laowang".equals(name)) {4         list.add(prefix + name);5     }

Replace:

1     if("laowang".equals(name)) {2         String prefix = "gebi";3         list.add(prefix + name);4     }

5. Avoid using try... catch in the loop and try... catch in the outer ring of the loop.

  

6. try... catch should not be too large.

Do not put useless code, that is, code that does not throw an exception into try... catch blocks to reduce the size of try... catch code blocks.

Ensure code readability, maintainability, and robustness.

  

  7. Avoid creating object references in a loop.

Especially when the number of cycles is large.

1     while (i<1000) {2         Object object = new Object();3     }

Recommended:

1     Object object = null;2             3     while (i<1000) {4         object = new Object();

Each time a new Object () is created, the Object references the Object.

When the number of loops is large, for example, in the first type, JVM will create a reference of 1000 objects, while in the second type, there is only one Object reference in the memory. This greatly saves the memory space.

  8. Do not use static variables at will.

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

The heap memory occupied by the static variable is released only after the end of the program in which the variable belongs. Static variable lifecycle = Class lifecycle.

  9. Do not create unused objects or import unused classes.

  10. Use an I/O Stream with buffer:

Buffered I/O streams can greatly improve I/O efficiency. BufferedWriter, BufferedReader, BufferedInputStream, and BufferedOutputStream.

  11. Use toString to convert the packaging data to a string.

    Integer I = 1;

Ranking of speed for converting packaging data to string method:

I. toString> String. valueOf (I)> "" + I

  

 12. Map traversal efficiency: entrySet> keySet

1 // entrySet () 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} 7 8 // up and down comparison 9 10 // keySet () 11 for (String key: map. keySet () {12 String value = map. get (key); 13 System. out. println (key + ":" + value); 14}

  

13. The Iterator and forEach () sets are traversed and rounded up.

Introduction to algorithms: algorithms are designed to improve space efficiency and time efficiency. However, time and space cannot coexist.

Time Efficiency: Iterator> forEach ()

Code readability: forEach ()> Iterator

 1     //Iterator 2     Set<Entry<String, String>> entrySet = map.entrySet(); 3     Iterator<Entry<String, String>> iter = entrySet.iterator(); 4       5     while (iter.hasNext()) { 6         Entry<String, String> entry = iter.next(); 7         String key = entry.getKey(); 8         String value = entry.getValue(); 9         System.out.println(key + " : " + value);10      } 

Comparison:

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     }

I personally think: Iterator is recommended to traverse the set when processing big data.

However, when processing small data, forEach () is used for readability and later maintenance ().

Both of them should be used in combination.

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.