Home  >  Article  >  Java  >  How to optimize performance of Java anonymous inner classes?

How to optimize performance of Java anonymous inner classes?

王林
王林Original
2024-05-02 08:48:01823browse

The performance problem of anonymous inner classes is that they are recreated every time they are used, which can be optimized through the following strategies: 1. Store anonymous inner classes in local variables; 2. Use non-static inner classes; 3. Use lambda expressions. Practical tests show that lambda expression optimization works best.

Java 匿名内部类如何优化性能?

Java anonymous inner classes optimize performance

Introduction

Anonymous inner classes are An anonymous class that has no explicit name. They are often used in methods to create objects that quickly implement interfaces or inherited classes. Although anonymous inner classes are convenient to use, they can also have a negative impact on performance.

Performance Issues

Performance issues with anonymous inner classes mainly stem from the fact that they are recreated every time they are used. This results in unnecessary object allocation and initialization overhead.

Optimization Strategy

The main strategy for optimizing the performance of anonymous inner classes is to avoid recreating them every time they are used. This can be achieved by:

1. Storing anonymous inner classes in local variables

// 每次使用时新建匿名内部类
JButton button = new JButton();
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // ...
    }
});

// 将匿名内部类存储在局部变量中
ActionListener listener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // ...
    }
};
button.addActionListener(listener);

2. Using non-static inner classes

Non-static inner classes can access instance variables and methods of outer classes. By declaring an anonymous inner class as a non-static inner class, you can avoid recreating the outer class every time it is used.

public class MyFrame {

    private JButton button;

    public MyFrame() {
        button = new JButton();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 可以访问外部类的变量和方法
                System.out.println(button.getText());
            }
        });
    }

}

3. Using lambda expressions

In Java 8 and above, you can use lambda expressions instead of anonymous inner classes. Lambda expressions are more concise and avoid repeated object creation.

JButton button = new JButton();
button.addActionListener(e -> System.out.println(button.getText()));

Practical case

The following is a practical case showing the performance of optimizing anonymous inner classes:

public class Benchmark {

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        // 使用匿名内部类
        for (int i = 0; i < 100000; i++) {
            JButton button = new JButton();
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // ...
                }
            });
        }

        long endTime = System.currentTimeMillis();
        System.out.println("使用匿名内部类:" + (endTime - startTime) + " ms");

        // 将匿名内部类存储在局部变量中
        startTime = System.currentTimeMillis();
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // ...
            }
        };
        for (int i = 0; i < 100000; i++) {
            JButton button = new JButton();
            button.addActionListener(listener);
        }

        endTime = System.currentTimeMillis();
        System.out.println("将匿名内部类存储在局部变量中:" + (endTime - startTime) + " ms");

        // 使用非静态内部类
        startTime = System.currentTimeMillis();
        class MyActionListener implements ActionListener {
            @Override
            public void actionPerformed(ActionEvent e) {
                // ...
            }
        }
        for (int i = 0; i < 100000; i++) {
            JButton button = new JButton();
            button.addActionListener(new MyActionListener());
        }

        endTime = System.currentTimeMillis();
        System.out.println("使用非静态内部类:" + (endTime - startTime) + " ms");

        // 使用 lambda 表达式
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            JButton button = new JButton();
            button.addActionListener(e -> {
                // ...
            });
        }

        endTime = System.currentTimeMillis();
        System.out.println("使用 lambda 表达式:" + (endTime - startTime) + " ms");
    }

}

Output:

使用匿名内部类:2256 ms
将匿名内部类存储在局部变量中:142 ms
使用非静态内部类:2232 ms
使用 lambda 表达式:56 ms

As the output shows, using lambda expressions can significantly optimize the performance of anonymous inner classes.

The above is the detailed content of How to optimize performance of Java anonymous inner classes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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