Does optimized imports improves performance?

Many of us have an idea that we optimize imports to improve performance.

We are told that we should import only the specific classes we need instead of whole packages.

import java.util.*;
import java.util.ArrayList;
import java.util.Map;

But does this really improve performance?


Let’s compare the bytecode generated after compilation to understand the difference.
We prepare two classes as below and generate their bytecode by compiling using the javac command –

A sample code with whole package imported A sample code with just the required classes imported
import java.util.*;

public class WholePackage {
ArrayList arrayList;
}

import java.util.ArrayList;

public class JustTheClass {
ArrayList arrayList;
}

Let’s use the Java’s code disassembler to see how it would be interpreting the bytecode.
we run the following commands on the class files to disassemble them –

javap -c WholePackage > WholePackage.out javap -c JustTheClass > JustTheClass.out
Compiled from “WholePackage.java”
public class WholePackage {
java.util.ArrayList arrayList;
 

public WholePackage();

Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object.””:()V
4: return
}

Compiled from “JustTheClass.java”
public class JustTheClass {
java.util.ArrayList arrayList;

public JustTheClass();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object.””:()V
4: return
}

Surprisingly or may be to my ignorance, the disassembled code is same for both. We can safely conclude that there’s no performance gain from exclusively importing classes instead of importing the whole package.


Then why is it a bad practice to import the whole package?

There are bigger risks than just performance.

Say I have a class named ArrayList in my package (of course i am not advising to make your classes named same to the java library ones) and I am also using java.util.HashMap in my Class. If I import java.util.* there can be incorrect imports at compile time that can go undetected.

Or the other way round if I have some classes like say GreatlyNamedAwesomeClass and I am also using a third party libraries (say import weirdjava.customlang.*; )  and the third party developers somehow also added a class named GreatlyNamedAwesomeClass in their next release… I would have some trouble making things compatible if I need to.

Have a look how my code broke as my package’s ArrayList is not having an add method (luckily, at least the compiler could catch it).

Cannot resolve method 'add(java.lang.String)'

So the primary reason for not using the wildcard imports and to exclusively import the classes is to avoid ambiguity and not performance optimization.