I am busy with a little Java program for a school project, and my import list became longer and longer. This made me wonder if it is better to import all at once:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Or to import necessary classes one by one:
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;
I can imagine, with really big projects, the import list can become really long. So are there any performance considerations?
Found answer here, link provided by Guo Song:
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