注释会减慢解释型语言的速度吗?

76 投票
11 回答
18257 浏览
提问于 2025-04-15 22:07

我问这个问题是因为我在用Python,不过这也可能适用于其他解释型语言,比如Ruby、PHP和JavaScript。

我想知道,当我在代码里留评论的时候,是不是会让解释器变慢?根据我有限的理解,解释器会把程序里的表达式当作字符串读取,然后把这些字符串转换成代码。看起来每次它解析一个评论的时候,都是在浪费时间。

真的是这样吗?在解释型语言中,评论有没有什么特别的约定,或者说这个影响其实很小?

11 个回答

24

评论通常在解析阶段或者之前就被去掉了,而解析的速度非常快,所以实际上评论不会影响初始化的时间。

36

我写了一个简单的Python程序,代码大概是这样的:

for i in range (1,1000000):
    a = i*10

这个程序的想法是,进行一个简单的计算很多次。

我测了一下,运行这个程序大约花了0.35±0.01秒。

然后我把整个《钦定版圣经》插入到程序里,代码变成了这样:

for i in range (1,1000000):
    """
The Old Testament of the King James Version of the Bible

The First Book of Moses:  Called Genesis


1:1 In the beginning God created the heaven and the earth.

1:2 And the earth was without form, and void; and darkness was upon
the face of the deep. And the Spirit of God moved upon the face of the
waters.

1:3 And God said, Let there be light: and there was light.

...
...
...
...

Even so, come, Lord Jesus.

22:21 The grace of our Lord Jesus Christ be with you all. Amen.
    """
    a = i*10

这次运行的时间大约是0.4±0.05秒。

所以答案是是的。在循环中加上4MB的注释确实会对运行时间产生可测量的影响。

108

在Python中,源文件在执行之前会先被编译成一种叫做.pyc的文件,而在这个过程中,注释会被去掉。所以,如果你有很多很多的注释,可能会让编译的时间变慢,但它们不会影响程序运行的速度。

撰写回答