在 perl 中使用常量的最佳实践
Best practices of using constant in perl
我刚开始学习perl,我才知道,常量在perl中被当作子程序处理。我想知道如果每次都在调用子程序并且 CPU 需要使用 stack/jump 指令,为什么使用常量是一个好习惯?
这是一个合理的担忧,但实际上没有函数调用开销。
我们先看看constant pragma文档
When a constant is used in an expression, Perl replaces it with its value at compile time, and may then optimize the expression further. In particular, any code in an if (CONSTANT) block will be optimized away if the constant is false.
因此您无需为运行时的函数调用付费。
此外,在 Technical Notes
下它说
In the current implementation, scalar constants are actually inlinable subroutines. As of version 5.004 of Perl, the appropriate scalar constant is inserted directly in place of some subroutine calls, thereby saving the overhead of a subroutine call. See
Constant Functions in perlsub for details about how and when this happens.
我们应该注意“当前实现”短语,但我认为可以安全地期望它不会以会造成运行时惩罚的方式改变。
请阅读本节的其余部分,并确保看到 Caveats。
提到的Constant Functions in perlsub描述
Functions with a prototype of ()
are potential candidates for inlining. If the result after optimization and constant folding is either a constant or a lexically-scoped scalar which has no other references, then it will be used in place of function calls made without &
. Calls made using &
are never inlined. (See constant.pm for an easy way to declare most constants.)
这证实了一个通常是很好的效率明智的。
另一方面,请注意 constant
pragma 的使用可能会引发以下问题:您的代码中是否需要关注裸字的使用(可能会也可能不会)。
"good practice" 考虑了对不应更改的变量使用常量(只读)声明的编程 好处。这种做法通常会大大改进代码。
我刚开始学习perl,我才知道,常量在perl中被当作子程序处理。我想知道如果每次都在调用子程序并且 CPU 需要使用 stack/jump 指令,为什么使用常量是一个好习惯?
这是一个合理的担忧,但实际上没有函数调用开销。
我们先看看constant pragma文档
When a constant is used in an expression, Perl replaces it with its value at compile time, and may then optimize the expression further. In particular, any code in an if (CONSTANT) block will be optimized away if the constant is false.
因此您无需为运行时的函数调用付费。
此外,在 Technical Notes
下它说
In the current implementation, scalar constants are actually inlinable subroutines. As of version 5.004 of Perl, the appropriate scalar constant is inserted directly in place of some subroutine calls, thereby saving the overhead of a subroutine call. See Constant Functions in perlsub for details about how and when this happens.
我们应该注意“当前实现”短语,但我认为可以安全地期望它不会以会造成运行时惩罚的方式改变。
请阅读本节的其余部分,并确保看到 Caveats。
提到的Constant Functions in perlsub描述
Functions with a prototype of
()
are potential candidates for inlining. If the result after optimization and constant folding is either a constant or a lexically-scoped scalar which has no other references, then it will be used in place of function calls made without&
. Calls made using&
are never inlined. (See constant.pm for an easy way to declare most constants.)
这证实了一个通常是很好的效率明智的。
另一方面,请注意 constant
pragma 的使用可能会引发以下问题:您的代码中是否需要关注裸字的使用(可能会也可能不会)。
"good practice" 考虑了对不应更改的变量使用常量(只读)声明的编程 好处。这种做法通常会大大改进代码。