Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java import vs code performance

Tags:

java

import

I am wondering if i included many import in my java program, would it affect the performance of my code (for example, program will be slower)? Is the logic behind the import in Java the same as include in C?

like image 249
newbie Avatar asked Feb 26 '11 06:02

newbie


People also ask

Do imports slow down Java?

No. Imports are purely a compile time construct ... syntactic sugar. The imports tell the Java compiler how to map identifiers in the source code to fully qualified class names.

Do unused imports affect performance?

Unused imports have no performance impact at runtime.

Do wildcard imports affect performance?

There is no performance difference between a specific import and a wildcard import declaration. The information for the classes in imported package is not read in at compile time or run time unless the class is used in the program.

Why is it better to avoid * in import statements in Java?

Wildcard imports tell java compiler to search for class names in the given package. Hence, using wild card imports, the compile-time performance may lower a bit.


1 Answers

would it affect the performance of my code (for example, program will be slower)?

No, it wouldn't affect performance of your code.

The binaries (the class files) do not increase in size as the import is not implemented with any cut-and-paste mechanism.

It is merely a syntactic sugar for avoiding to have to write for instance

java.util.List<java.math.BigInteger> myList =         new java.util.ArrayList<java.math.BigInteger>(); 

Here is a little test demonstrating this:

aioobe@e6510:~/tmp$ cat Test.java  import java.util.*;  public class Test {     public static void main(String[] args) {         List<Integer> myInts = new ArrayList<Integer>();     } } aioobe@e6510:~/tmp$ javac Test.java aioobe@e6510:~/tmp$ md5sum Test.class  523036e294b17377b4078ea1cb8e7940  Test.class 

(modifying Test.java)

aioobe@e6510:~/tmp$ cat Test.java    public class Test {     public static void main(String[] args) {         java.util.List<Integer> myInts = new java.util.ArrayList<Integer>();     } } aioobe@e6510:~/tmp$ javac Test.java aioobe@e6510:~/tmp$ md5sum Test.class  523036e294b17377b4078ea1cb8e7940  Test.class 

Is the logic behind the import in Java the same as include in C?

No, an #include is a preprocessor directive and is implemented with a cut-and-paste mechanism.

like image 191
aioobe Avatar answered Sep 17 '22 18:09

aioobe