有 Java 编程相关的问题?

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

java哪个for循环头性能更好?

我在Android文档中看到了以下内容:

int n = getCount();

for (int i = 0; i < n; i ++) {
    // do somthing
}

但我已经习惯于看到和做:

for (int i = 0; i < getCount(); i ++) {
    // do somthing
}

我很好奇一个是否比另一个更有效率?在这两种情况下究竟发生了什么?当用第二种方法调用getCount()时,计算机是否必须分配另一个变量?或者这仅仅是一个代码清洁或偏好的问题


共 (3) 个答案

  1. # 1 楼答案

    这是JDK1的javac编译器所做的。6.0_21为两种情况生成:

    第一种情况:

    int n = getCount();
    
    for (int i = 0; i < n; i ++) {
        // do something
    }
    

    编译字节码:

    invokestatic example/Test/getCount()I
    istore_1
    iconst_0
    istore_2
    goto 10
    ... // whatever code in the loop body
    iinc 2 1
    iload_2
    iload_1
    if_icmplt 6
    return
    

    第二种情况:

    for (int i = 0; i < getCount(); i ++) {
        // do something
    }
    

    编译字节码:

    iconst_0
    istore_1
    goto 8
    ... // whatever code in the loop body
    iinc 1 1
    iload_1
    invokestatic example/Test/getCount()I
    if_icmplt 4
    return
    

    结果代码可能不同,但根据getCount(),运行时可能会优化执行。一般来说,第一个代码似乎效率更高,特别是当getCount()执行一些复杂的操作以返回其值时

  2. # 2 楼答案

    第一个比另一个更有效

    在第一个场景中,只调用一次getCount,而在第二个场景中,每次条件检查都调用getCount,这会增加循环的执行时间

  3. # 3 楼答案

    问题不在于性能,第二个问题可能会更慢,因为

    public class stuff {
        static int getCount() {
            System.out.println("get count");
            return 5;
        }
        public static void main(String[] args) {
            for (int i = 0; i < getCount(); i ++) {
                System.out.println("loop " + i);
            }
        }
    
    }
    

    有输出

    get count
    loop 0
    get count
    loop 1
    get count
    loop 2
    get count
    loop 3
    get count
    loop 4
    get count
    

    您看到循环中的getCount被执行多次了吗?为什么这不是一个问题?你如何比较不同事物的表现?如果行为无关紧要,那么您可以很高兴地将nopthemostcomplexComputionInThe世界进行比较