在 Java 中,未使用的导入声明会占用内存吗? [英] Does an unused import declaration eat memory, in Java?

查看:52
本文介绍了在 Java 中,未使用的导入声明会占用内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

未使用的导入是否会像这样 - import android.widget.RelativeLayout; 占用内存?只是想知道它有多少或只是有价值吗?也许这是一个愚蠢的问题,但我还没有找到答案.

解决方案

不,它们不占用任何内存.导入仅被编译器用于在编译时解析类名.

编译器将每个类名更改为完全限定名.并删除导入语句.所以,import 语句不会变成字节码.

通配符导入唯一可能出现的问题是命名空间冲突,即当两个不同的包中定义了同名的两种类型时,使用通配符导入这些包会导致所使用的类型发生名称冲突.

>

要查看编译器如何替换 import 语句,您可以使用 javap 命令生成类的字节码.考虑以下代码:

import java.util.*;导入 java.util.regex.*;公共类测试{公共静态无效主(字符串 [] args){}}

只需编译上面的代码,并使用以下命令检查字节码:

javap 测试

它给出以下输出:

公共类测试{公共测试();public static void main(java.lang.String[]);}

所以,可以看到String类型被替换为它的全限定名java.lang.String,字节码中没有import语句.>

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 stupid question, but I haven't found answer.

解决方案

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.

这篇关于在 Java 中,未使用的导入声明会占用内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆