与 Java 6 相比,Java 8 的 GUI 性能较差
2022-09-01 10:58:44
在 Java 6 中,下面的代码按预期运行,但在 Java 8 中,它需要花费更多的时间。有趣的是,组件使用相同的方法来启用和禁用组件,但禁用调用比启用调用花费的时间要长得多,几乎是启用调用的两倍。在 Java 8 中禁用比在 Java 1.6 中禁用所需的时间要长得多。问题是为什么会发生这种情况?这是 Java 8 的性能问题吗?setEnable()
以下是 Java 6 的结果:
Sun Microsystems Inc. 1.6.0_45
Initializing GUI
GUI initialized in 1105 ms
Disabling
Disabled in 687 ms
Enabling
Enabled in 375 ms
以下是 Java 8 的结果:
Oracle Corporation 1.8.0_25
Initializing GUI
GUI initialized in 604 ms
Disabling
Disabled in 6341 ms
Enabling
Enabled in 370 ms
代码:
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TestGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
public TestGUI() {
initGUI();
}
public void actionPerformed(ActionEvent e) {
String text;
if(e.getActionCommand().equals("Enable-ALL")){
enableAll();
text= "Disable-ALL";
}
else{
disableAll();
text= "Enable-ALL";
}
((JButton)e.getSource()).setText(text);
((JButton)e.getSource()).setEnabled(true);
}
private void initGUI() {
long m = System.currentTimeMillis();
System.out.println("Initializing GUI");
setTitle(System.getProperty("java.vendor") + " " + System.getProperty("java.version"));
setLayout(new FlowLayout());
JButton b = new JButton("Disable-ALL ");
b.addActionListener(this);
add(b);
for (int i = 1; i < 10001; i++) {
b = new JButton("Button " + i);
add(b);
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
m = System.currentTimeMillis() - m;
System.out.println("GUI initialized in " + m + " ms");
}
private void disableAll() {
long m = System.currentTimeMillis();
System.out.println("Disabling");
for (Component c : getContentPane().getComponents()) {
c.setEnabled(false);
}
m = System.currentTimeMillis() - m;
System.out.println("Disabled in " + m + " ms");
}
private void enableAll() {
long m = System.currentTimeMillis();
System.out.println("Enabling");
for (Component c : getContentPane().getComponents()) {
c.setEnabled(true);
invalidate();
}
m = System.currentTimeMillis() - m;
System.out.println("Enabled in " + m + " ms");
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
System.out.println(System.getProperty("java.vendor") + " "
+ System.getProperty("java.version"));
new TestGUI();
}
});
}
}