Table of Contents
1. Minimize the visibility of class members and methods
2. Use displacement operations instead of multiplication and division
3. Minimize repeated calculations of variables
4. Do not catch RuntimeException
5. Use local variables to avoid allocation on the heap
6. Reduce the scope of variables
7. Lazy loading strategy
8. Access static variables directly using the class name
9. Use StringBuilder for string splicing
10. Rewrite the HashCode of the object
11. Initialization of collections such as HashMap
12. Create object reference inside the loop
13. Traverse the Map using EntrySet method
14. Do not use the same Random in multiple threads
15. It is recommended to use LongAddr for auto-increment
16. Use less reflection in programs
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?

May 09, 2023 am 08:16 AM
java

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;
Copy after login

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");
}
Copy after login

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);
}
Copy after login

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;
    }
}
Copy after login

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);
}
Copy after login

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();
Copy after login

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());
    }
}
Copy after login

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();
}
Copy after login

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());
}
Copy after login

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();
    }
Copy after login

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();
    }
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles