注释数量的增加会增加执行时间吗?

Gok*_* KP 6 java comments jdk1.5 execution-time

考虑以下情况:

案例1 :(评论较少for loop)

import java.io.IOException;

public class Stopwatch { 
    private static long start;
    public static void main(String args[]) throws IOException {
        start = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            /**
             * Comment Line 1
             * Comment Line 2
             * Comment Line 3
             * Comment Line 4
             */
        }
        System.out.println("The time taken to execute the code is: " + (System.currentTimeMillis() - start)/1000.0);
    }
}
Run Code Online (Sandbox Code Playgroud)

执行代码所需的时间是:2.259

案例2 :(更多评论for loop)

import java.io.IOException;

public class Stopwatch { 
    private static long start;
    public static void main(String args[]) throws IOException {
        start = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            /**
             * Comment Line 1
             * Comment Line 2
             * Comment Line 3
             * Comment Line 4
             * Comment Line 5
             * Comment Line 6
             * Comment Line 7
             * Comment Line 8
             */
        }
        System.out.println("The time taken to execute the code is: " + (System.currentTimeMillis() - start)/1000.0);
    }
}
Run Code Online (Sandbox Code Playgroud)

执行代码所需的时间是:2.279

案例3 :(没有评论,空for loop)

import java.io.IOException;

public class Stopwatch { 
    private static long start;
    public static void main(String args[]) throws IOException {
        start = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {

        }
        System.out.println("The time taken to execute the code is: " + (System.currentTimeMillis() - start)/1000.0);
    }
}
Run Code Online (Sandbox Code Playgroud)

执行代码所需的时间是:2.249

配置:JDK 1.5,第3代i5,4GB Ram.

问题:如果我们添加更多注释,程序是否需要更多时间来执行?为什么?

Jon*_*eet 15

问题:如果我们添加更多注释,程序是否需要更多时间来执行?为什么?

不.评论对执行没有影响.

他们将放慢下来编译一个微小的一点-但即使这应该是感觉不到的,除非你有一个荒谬的评论数.

你注意到的"效果"更多地与你计时的方式有关 - System.currentTimeMillis用于基准测试是一个坏主意; 您应该使用,System.nanos因为它通常使用更高精度的时钟(仅适用于计时,而不适用于确定"挂钟"时间).此外,通常基准程序应该运行其"目标"代码足够长的时间,以便在实际测量之前预热JIT编译器等.然后,您需要考虑可能同时在系统上运行的其他内容.基本上,编写一个好的基准测试涉及很多.如果您将来要编写任何重要的基准测试,我建议您查看Caliper.

您可以通过注释来验证没有区别 - 编译代码然后运行

javap -c Stopwatch
Run Code Online (Sandbox Code Playgroud)

你可以看一下字节码.你会发现不同版本之间没有区别.