Java programming code performance optimization

  • 2020-04-01 04:23:04
  • OfStack

I. the purpose of our action:

1. Efficiency (most important)

2. Readability for later maintenance. (also important)

Ii. Code optimization requirements:

1. Reduce the size of your code.

2. Make your code run more efficiently.

Iii. Common code optimization:

1. Try to reuse objects:

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

When it comes to frequently erasing concatenated strings. Remember to use StringBuilder/StringBuffer

Such as:


  ArrayList<String> list;
  //Omit list initialization.
  StringBuilder builder = new StringBuilder(); 
  for (String s : list) {
    builder.append(s);
  }
  String result = builder.toString();

Reason: the Java virtual machine takes time not only to generate objects, but also to process and recycle them, and generating too many objects is bound to have an impact on program performance.

2. Use local variables whenever possible:

Local variables are created in the stack, which is fast to create and will disappear when used up, without additional garbage collection.

While static variables, instance variables, etc., are created in the heap, which is slow to create and also relies on the Java garbage collection mechanism.

3. Timely closing of the stream:

In Java program development, it is important to remember to close the stream after the I/O, database operation.

Reason: leaving the stream open can cause a lot of overhead to the system and even serious consequences to the data.

4. Use lazy loading

Lazy load: this object is created when it is needed.

Such as:


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

                Replace with:


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

5. Avoid using try in loops... Catch, using try on the outer loop... The catch

6. Try... Catch should not be too large.

Don't put any dead code, or code that doesn't throw an exception, into the try... In the catch block, decrease the try... Size of catch code block.

Ensure that the code is readable, easy to maintain, and robust.

7. Try to avoid creating references to objects within the loop.

Especially if there's a lot of circulation.


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

                      It is suggested to change to:


  Object object = null;
  while (i<1000) {
    object = new Object();

Each time new Object() is created, the Object Object reference points to the Object Object.

When the loop is repeated many times, such as in the first case, the JVM creates 1000 Object references, while in the second case there is only one Object reference in memory. This greatly saves memory space.

8. Don't use static variables.

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

The heap memory occupied by a static variable is not freed until the end of the program in which the variable resides. The static variable life cycle = the class life cycle.

Don't create unused objects or import unused classes.

10. Use buffered I/O streams:

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

11. Wrap the class data into a string using: toString

The Integer I = 1;

Wrapper class data conversion to string method speed ranking:

I.t oString > String. The valueOf (I) > "" + i 

12.Map traversal efficiency: entrySet > keySet


  //entrySet()
  for (Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key + " : " + value);
  }
  
  //Upper and lower contrast
  
  //keySet()
  for (String key : map.keySet()) {
  String value = map.get(key);
  System.out.println(key + " : " + value);
  } 

13. Ergodic rounding of the sets Iterator and forEach().

Algorithm introduction: algorithm is to improve the efficiency of space and time. But often time and space cannot coexist.

Time efficiency: Iterator > The forEach ()

Code readability: forEach() > The Iterator


  //Iterator
  Set<Entry<String, String>> entrySet = map.entrySet();
  Iterator<Entry<String, String>> iter = entrySet.iterator();
   
  while (iter.hasNext()) {
    Entry<String, String> entry = iter.next();
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key + " : " + value);
   } 

Contrast:


  //forEach()
  for (Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key + " : " + value);
  }

                      Personal opinion: it is recommended to use Iterator to traverse collections when working with big data.

But for small data, forEach() is still used for readability and post-maintenance.

When used in combination, both should be mastered.


Related articles: