java - 评论数量的增加是否会增加执行时间?

标签 java comments execution-time java-5

考虑以下情况:

案例一:(for循环中注释较少)

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循环中)

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 循环)

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 内存。

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

最佳答案

Question: If we add more comments, does the program takes more time to execute? Why?

没有。评论对执行没有影响。

它们会降低编译器的速度 微小 - 但即使这样也应该是察觉不到的,除非你有可笑数量的注释。

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

你可以验证没有区别只是因为评论 - 编译你的代码然后运行

javap -c Stopwatch

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

关于java - 评论数量的增加是否会增加执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18821194/

相关文章:

java - 如果 List<List<T>> 结构中不存在新列表,如何更好地测试和创建新列表?

java - 读取 100Mb xlsx 文件在 java 中解析它并将其存储到 mongodb 中?快速地

Java 8 Generic 的 Generic for Monad Transformer

javascript:编译器解释//作为正则表达式中的注释的一些问题

java - Eclipse 注释类型之间有什么区别?

python - 如何通过替换 python 中的 for 循环来减少算法的执行时间

java - Eclipse EE 格式错误

c - 用 C 编写注释的更好方法是什么?

c# - 在 C# 中测量执行时间

sql-server - 如何提高查询性能