Consider I use a type X
in my java compilation unit from package foo.bar
and X
is not defined in the compilation unit itself nor is it directly imported. How does a java compiler resolve X
now efficiently? There are a few possibilities where X
could reside:
X
might be imported via a star importa.b.*
X
might reside in the same package as the compilation unitX
might be a language type, i.e. reside injava.lang
The problem I see is especially (2.). Since X
might be a package-private type, it is not even required that X
resides in a compilation unit that is named X.java
. Thus, the compiler must look into all entries of the class path and search for any classes in a package foo.bar
, it then must read every class that is in package foo.bar
to check whether X
is included.
That sounds very expensive. Especially when I compile only a single file, the compiler has to read dozens of class files only to find a type X
. If I use a lot of star imports, this procedure has to be repeated for a lot of types (although class files won't be read twice, of course).
So is it advisable to import also types from the same package to speed up the compilation process? Or is there a faster method for resolving an unimported type X
which I was not able to find?
If the compiler did it that way, it would be expensive.
But what actually happens is that it builds an in-memory data structure containing all of the class names on the classpath, bootclasspath and sourcepath, and uses that for all of the classname resolutions in all classes that are compiled in the
javac
run.No, and no. It will make almost no difference. And besides, this is unlikely to be a significant bottleneck if you use the compiler how it was designed to be used.
It is better to do the imports in a way that gives the most readable and reliable code.