简体   繁体   中英

effects of extra imported classes in java

in http://source.android.com/source/code-style.html

I read about use fully qualify imports. But I am curious about the negative affects of not using imports explicitly. For instance, if I use the following code

package blabla;
import foo.*;
import hee.*;
import lee.*;
...
...
public class ImportKing {
...
}

from my understanding, when this class--ImportKing is used anywhere in the project, the classloader will load any classes it imported, therefore will consume extra system memory for needless imports.

testing code:

//import java.*;
public class ImportKing {
    public static void main(String[] args) {
        while(true) {
            System.out.println("running");
        }
    }
}

testing result:

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

shanwu 3316 39.8 0.6 3182012 52196 pts/0 Sl+ 09:25 0:03 java ImportKing with extra imports

shanwu 3440 43.7 0.6 3182012 52752 pts/0 Sl+ 09:27 0:03 java ImportKing without extra imports

I didn't see any negative effects on program performance for extra imports. Is extra imports handled by java compiler, so we don't have problem like wasting system memory?

An import statement does absolutely nothing at runtime.

An import statement simply makes it possible for you to use simple names of types (and their members) in your source code rather than fully qualified names.

Q: the classloader will load any classes it imported,

A: No, the class loader will be invoked when a class is needed (for example, calling a constructor). This has nothing to do with "imports" in your source code.

Q: therefore will consume extra system memory for needless imports.

A: No: classes are not loaded needlessly; memory is not "wasted".

SUGGESTION:

Here are two good links on the basics of Java class loading:

Here is what the Java specification has to say about "import":

http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5

An import declaration makes types or members available by their simple names only within the compilation unit that actually contains the import declaration. The scope of the type(s) or member(s) introduced by an import declaration specifically does not include the PackageName of a package declaration, other import declarations in the current compilation unit, or other compilation units in the same package.

An "import" is a compile-time construct to simplify identifying a "name" with (perhaps one of many different) "class definition(s)". It does not affect runtime behavior; it is completely seperate from "class loading".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM