Does an unused import declaration eat memory, in Java?

后端 未结 5 1727
渐次进展
渐次进展 2020-12-05 17:56

Does an unused import like so - import android.widget.RelativeLayout; eat memory? Just want to know about how much or just is it valuable? Maybe this is stu

5条回答
  •  半阙折子戏
    2020-12-05 18:04

    No they don't take any memory. Imports are just used by compiler to resolve class names at compile time.

    Compiler changes each class name to fully qualified name. And removes the import statement. So, the import statement doesn't make it to byte code.

    The only issue that can come up with wildcard import is namespace conflict, i.e., when two types with the same name is defined in two different packages, then importing those packages with wildcards will cause name conflict for that type used.


    To see how compiler replaces the import statement, you can generate the byte code of your class using javap command. Consider the below code:

    import java.util.*;
    import java.util.regex.*;
    
    public class Test {
        public static void main(String[] args) {
    
        }
    }
    

    Just compile the above code, and check the byte code using the following command:

    javap Test
    

    It gives out following output:

    public class Test {
      public Test();
      public static void main(java.lang.String[]);
    }
    

    So, you can see that String type is replaced with it's fully qualified name java.lang.String, and there is no import statement in byte code.

提交回复
热议问题