“我的"怎么样比“本地"更快在Perl? [英] How is "my" faster than "local" in Perl?

查看:67
本文介绍了“我的"怎么样比“本地"更快在Perl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用 PerlMonks:我和本地人之间的区别

Quoting from PerlMonks: The difference between my and local,

但是在现实生活中,它们的工作原理几乎相同吗?是的.有点.那么什么时候应该使用它们?

But in real life, they work virtually the same? Yes. Sort of. So when should you use them?

在可能的情况下使用我的"(速度比本地快)...

我知道mylocal之间在词汇和动态范围方面的差异,如

I know the lexical vs dynamic scoping difference between my and local, as discussed in this SO thread, but I am not sure why my is "faster".

当说Perl中的my变量比local变量快时,我们到底是什么意思?

What exactly do we mean when we say that a my variable is faster than a local variable in Perl?

推荐答案

在变量上使用local意味着需要将其先前的状态压入某个位置的堆栈中,并在退出本地范围时再次恢复.在变量上使用my只会创建一个全新的变量,该变量以相同的名称遮盖先前的变量-先前的变量完全未被修改,不需要保存在任何地方.当退出本地作用域并且再次可见时,它只是处于等待状态.

Using local on a variable means that its previous state needs to be pushed onto a stack somewhere and restored again when the local scope is exited. Using my on a variable simply creates an entirely new variable that shadows the previous variable with the same name -- the previous one is entirely untouched, and does not need to be saved anywhere. It is simply lying in wait when the local scope is exited and it is visible again.

这种压入/弹出堆栈需要占用资源;要确保这项工作正常进行,有很多工作要做. (请考虑一些情况,例如在本地范围内引发异常,或者正在执行信号处理程序.我敢肯定,您还会想到更多.)

This pushing/popping to a stack takes resources; there's a lot of work under the hood to ensure that this works properly. (Consider cases such as an exception being thrown while in local scope, or a signal handler being executed. I'm sure you can think of more.)

除了提高效率外,使用my更合​​乎逻辑.当程序员引入局部变量$ foo时,您不必担心$ foo先前版本的语义原因,可能已经包含了什么数据,或者是否确实存在 $ foo已经创建.如果在某个时候删除了$ foo的较早声明,您的local $foo代码将被破坏,但是my $foo将会非常满意.成为一名优秀的程序员,并将您的代码放在封装良好的部分中,这意味着您将尽可能多地使用词法作用域.完全有可能编写大型应用程序,而根本不需要包/全局范围的变量,尤其是当您使用设计良好的OO类时.

Besides being more efficient, using my is much more logical. As a programmer introducing a local variable $foo, you don't need to worry about the semantic reason for the previous version of $foo, what data might already be in it, or indeed if there was a $foo already created. If sometime down the road the earlier declaration of $foo is removed, your local $foo code will break, but my $foo will be perfectly happy. Be a good programmer and keep your code in well-encapsulated pieces, which means using lexical scoping as much as you can. It's quite possible to write a large application and never need variables of package/global scope at all, especially when you use well-designed OO classes.

这篇关于“我的"怎么样比“本地"更快在Perl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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