Perl:为什么在循环中声明(我的)变量会更慢? [英] Perl: Why is it slower to declare (my) variables inside a loop?

查看:95
本文介绍了Perl:为什么在循环中声明(我的)变量会更慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序与口译员的POV有什么区别:

What's the difference, from the interpreter's POV, between the following the following programs:

#!/usr/bin/perl -w

use strict;

for (1..10000000) {
    my $jimmy = $_**2;
}

#!/usr/bin/perl -w

use strict;

my $jimmy;
for (1..10000000) {
    $jimmy = $_**2;
}

第一个程序的时间"报告:

"time" reports for the first program:

real    0m1.519s
user    0m1.513s
sys     0m0.004s

第二个:

real    0m1.023s
user    0m1.012s
sys     0m0.002s

推荐答案

Perl中的my声明有两个主要作用:一个编译时(其中在包含子项的暂存器上分配一个插槽,并确保在适当范围内对该名称的所有引用都解析为该特定暂存器插槽),以及一个运行时(其中将其重置值)该填充插槽为undef,或者如果您写为my $var = foo,则为某个特定值).

The my declaration in Perl has two primary effects; a compile-time one (wherein it allocates a slot on the containing sub's scratchpad, and makes sure that all references to that name within the proper scope are resolved to that particular scratchpad slot), and a runtime one (wherein it resets the value of that pad slot to undef, or to some particular value if you wrote my $var = foo).

当然,编译时部分的运行时成本为零,但是每次执行通过my声明时,运行时部分就会运行一次.正如其他人指出的那样,您的两个示例具有不同的性能,因为它们通常具有不同的语义 -一个在每次循环时都清除变量,而另一个则不.

The compile-time portion of course has zero amortized runtime cost, but the runtime portion is run once each time execution passes the my declaration. As others have pointed out, your two examples have different performance because they have different semantics in general -- one clears the variable every time through the loop, and the other doesn't.

这篇关于Perl:为什么在循环中声明(我的)变量会更慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆