Home >Java >javaTutorial >How to optimize Java code and what practical tips are available at work?

How to optimize Java code and what practical tips are available at work?

王林
王林forward
2023-05-09 08:16:071263browse

1. Minimize the visibility of class members and methods

Example:If it is a private method, delete it if you want to delete it

If a The service method of public, or a public member variable, should be deleted without thinking too much.

2. Use displacement operations instead of multiplication and division

Computers use binary representation, and displacement operations will greatly improve performance.

> Right shift is equivalent to dividing by 2;

>>> Unsigned right shift is equivalent to dividing by 2, but it will ignore the sign bit and fill the empty bits with 0s.

a = val << 3;
b = val >> 1;

3. Minimize repeated calculations of variables

We know that calling methods is costly, including creating stack frames, protecting the scene when calling methods, restoring the scene, etc.

//反例
for (int i = 0; i < list.size(); i++) {
  System.out.println("result");
}
//正例
for (int i = 0, length = list.size(); i < length; i++) {
  System.out.println("result");
}

When list.size() is very large, it reduces a lot of consumption.

4. Do not catch RuntimeException

RuntimeException should not be caught through catch statements, but should be avoided by coding means.

As shown in the following code, an array out-of-bounds exception may occur in the list.

Whether it is out of bounds can be judged in advance through the code, instead of waiting to catch an exception when it occurs.

Judge this way in advance, the code will be more elegant and efficient.

public String test1(List<String> list, int index) {
    try {
        return list.get(index);
    } catch (IndexOutOfBoundsException ex) {
        return null;
    }
}
//正例
public String test2(List<String> list, int index) {
    if (index >= list.size() || index < 0) {
        return null;
    }
    return list.get(index);
}

5. Use local variables to avoid allocation on the heap

Since heap resources are shared by multiple threads and are the main area where the garbage collector works, too many objects will cause GC pressure. , variables can be allocated on the stack through local variables. In this way, the variables will be destroyed when the method execution is completed, which can reduce the pressure on the GC.

6. Reduce the scope of variables

Pay attention to the scope of variables and minimize the creation of objects.

As shown in the following code, the variable s will be created every time the method is entered, and it can be moved inside the if statement.

public void test(String str) {
    final int s = 100;
    if (!StringUtils.isEmpty(str)) {
        int result = s * s;
    }
}

7. Lazy loading strategy

Try to adopt the lazy loading strategy and only create it when needed

String str = "月伴飞鱼";
if (name == "公众号") {
  list.add(str);
}
if (name == "公众号") {
  String str = "月伴飞鱼";
  list.add(str);
}

8. Access static variables directly using the class name

Use objects to access static variables. This method adds one more addressing operation. You need to first find the class corresponding to the variable, and then find the variable corresponding to the class.

 // 反例
int i = objectA.staticMethod();
 // 正例
int i = ClassA.staticMethod();

9. Use StringBuilder for string splicing

For string splicing, use StringBuilder or StringBuffer, do not use numbers.

//反例
public class StringTest {
    @Test
    public void testStringPlus() {
        String str = "111";
        str += "222";
        str += "333";
        System.out.println(str);
    }
}
//正例
public class TestMain {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("111");
        sb.append("222");
        sb.append(333);
        System.out.println(sb.toString());
    }
}

10. Rewrite the HashCode of the object

Rewrite the HashCode of the object, do not simply return a fixed value

Some students are developing overriding HashCode and Equals methods, Will return the value of HashCode to a fixed 0, and this is inappropriate

When these objects are stored in HashMap, the performance will be very low, because HashMap locates the Hash slot through HashCode, and there is a conflict. Only when this happens, linked lists or red-black trees are used to organize nodes, and 0 is returned fixedly, which is equivalent to invalidating the Hash addressing function.

11. Initialization of collections such as HashMap

When initializing collections such as HashMap, specify the initial value size

There are many such objects, such as ArrayList, StringBuilder, etc., by specifying the initial value The value size can reduce the performance loss caused by expansion.

Calculation of initial value size:

How to optimize Java code and what practical tips are available at work?

12. Create object reference inside the loop

Inside the loop Do not continuously create object references

//反例
for (int i = 1; i <= size; i++) {
    Object obj = new Object();    
}
//正例
Object obj = null;
for (int i = 0; i <= size; i++) {
    obj = new Object();
}

The first method will cause size Object object references to exist in the memory. If the size is large, memory will be consumed

13. Traverse the Map using EntrySet method

Using the EntrySet method, you can directly return the set object, which can be used directly; and using the KeySet method, you get a collection of keys, and you need to perform another get operation, which adds one more operation step. Therefore, it is more recommended to use the EntrySet method to traverse the Map.

Set<Map.Entry<String, String>> entryseSet = nmap.entrySet();
for (Map.Entry<String, String> entry : entryseSet) {
    System.out.println(entry.getKey()+","+entry.getValue());
}

14. Do not use the same Random in multiple threads

The seeds of the Random class will compete during concurrent access, resulting in reduced performance. It is recommended to use ThreadLocalRandom in a multi-threaded environment. kind.

 public static void main(String[] args) {
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        Thread thread1 = new Thread(()->{
            for (int i=0;i<10;i++){
                System.out.println("Thread1:"+threadLocalRandom.nextInt(10));
            }
        });
        Thread thread2 = new Thread(()->{
            for (int i=0;i<10;i++){
                System.out.println("Thread2:"+threadLocalRandom.nextInt(10));
            }
        });
        thread1.start();
        thread2.start();
    }

15. It is recommended to use LongAddr for auto-increment

Auto-increment operation can control thread safety through the combination of synchronized and volatile , or you can Use an atomic class (such as AtomicLong).

The speed of the latter is higher than the former, AtomicLong Using CAS for comparison and replacement will cause too many invalid spins when there are many threads. You can use LongAdder to replace AtomicLong for further progress. performance improvement.

public class Test {
    public int longAdderTest(Blackhole blackhole) throws InterruptedException {
        LongAdder longAdder = new LongAdder();
        for (int i = 0; i < 1024; i++) {
            longAdder.add(1);
        }
        return longAdder.intValue();
    }
}

16. Use less reflection in programs

The reflection function is very powerful, but it is implemented by parsing bytecode, and the performance is not very ideal.

In reality, there are many optimization methods for reflection, such as caching the reflection execution process (such as Method) and using multiplexing to speed up reflection.

After Java 7.0, a new package java.lang.invoke was added, and a new JVM bytecode instruction invokedynamic was added to support directly passing strings from the JVM level Make a call to the target method.

The above is the detailed content of How to optimize Java code and what practical tips are available at work?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete