gpt4 book ai didi

java - : import one by one or . * 哪个更好?

转载 作者:行者123 更新时间:2023-12-01 12:39:24 24 4
gpt4 key购买 nike

我正忙着为学校项目编写一个 Java 程序,我的导入列表变得越来越长。这让我想知道是否最好一次性导入:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

或者一一导入必要的类:

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;

import java.awt.event.ComponentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Point;

我可以想象,对于非常大的项目,导入列表可能会变得非常长。那么有什么性能方面的考虑吗?

找到答案 here ,郭松提供的链接:

The import directive is a compiler directive, it tells the compiler where to look for a class and allows to not have to always use fully qualified class names, e.g. java.util.HashMap. But the import directives themselves do not get put into the compiled bytecode files, the compiler compiles the fully qualified name into the .class file.

When used wiithout a wildcard, the directive explicitly tells the compiler to look for one specific file in the classpath. With a wildcard, the directive tells the compiler to look for the named package and to search in that package for possible matches every time any name needs to be matched. The latter version is probably going to take (a bit) longer for the compiler than the former.

In other words, the import directive cannot affect runtime code execution in any way. However, the import directive does affect compilation time. Additionally, I find that using import with wildcards makes the code less readable.

Actually, the cost of import statements question of the month on javaperformancetuning.com perfectly summarize this in its conclusion:

There is no runtime cost from using an import statement The compilation process can take a little more time with an import statement The compilation process can take even more time with a wildcard import statement For improved readability, wildcard import statements are bad practice for anything but >>throwaway classes The compilation overhead of non-wildcard import statements are minor, but they give readability benefits so best practice is to use them

最佳答案

不会影响程序的运行速度。

但是会影响程序的编译时间。

如果导入java.sql.*,那么在编译时编译器会一一导入包,因此编译时会产生开销

但是在运行时编译器会忽略编译器在编译时导入的所有未使用的导入语句,因此它不会影响程序的运行时速度。

通常最好通过完整限定名称导入而不是导入所有列表,这将提高代码的可读性和可维护性。

让我们看一个简单的案例:

     import java.util.*;

     import java.util.ArrayList;
import java.util.List;



//.when we write a program :..
List <String> someList = new ArrayList <String> ();
//...

当编译器遇到 List 这个词时,在第一种情况下,它需要确定 List 是否存在于该类集合中。在第二种情况下,它已经明确给出了,所以它更容易。

关于java - : import one by one or . * 哪个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25260952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com