有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android For循环,全局静态列表与本地列表

我只是想知道如果我执行以下操作,是否会有任何性能差异,RAM使用是否也会有任何差异

而不是做:

for (String str : Globals.stringArray)
{
    //do whatever
}

我这样做:

List<String> stringArray = Globals.stringArray;
for (String str : stringArray)
{
    //do whatever
}

循环使用本地列表而不是全局静态列表是否更好


共 (3) 个答案

  1. # 1 楼答案

    没有(显著的)性能差异,根据编译器的不同,您的代码可能会产生完全相同的字节码,因为您无论如何都在完全相同的对象上迭代。通常,您不应尝试在如此低的级别上调整性能,而应选择更具可读性和自我表达能力的方法:

    Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

    (引用Donald Knuth的话)

  2. # 2 楼答案

    您的代码应该执行完全相同的操作,因为您的局部变量不包含全局静态的副本,而是对它的引用

  3. # 3 楼答案

    编译器优化此代码后,中间语言中的结果将相同。所以,不会有任何区别