考虑以下情况:

情况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);
    }
}

执行代码所需的时间为: 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);
    }
}

执行代码所需的时间为: 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);
    }
}

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

配置:JDK 1.5,第三代i5、4GB Ram。

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

最佳答案



否。注释对执行没有影响。

它们会稍微降低编译器的速度-除非您的注释数量过多,否则即使这样做也不会被察觉。

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

您可以验证仅由于注释而没有区别-编译代码然后运行

javap -c Stopwatch

然后您可以查看字节码。您会看到不同版本之间没有区别。

08-05 05:42
查看更多