Search code examples
perlconstantssubroutine

Given constants are implemented as subroutines, is it actually a good practice to use them given the performance overhead?


I just started learning Perl. I came to know that a constant is treated as a subroutine. I wonder why the use of constants can be a good practice if every time it is making subroutine call and the CPU needs to use a stack/jump instruction?


Solution

  • That is a reasonable concern but there is in fact no function call overhead.

    Let's first have a look at constant pragma docs

    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.

    So you are not paying for a function call at runtime.

    Further, under Technical Notes it says

    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.

    We should take note of the "current implementation" phrase, but I think it's safe to expect this not to change in a way that would impose a runtime penalty.

    Please read the rest of this section, and make sure to see the Caveats.

    The mentioned Constant Functions in perlsub describes

    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.)

    This confirms that one is generally fine efficiency wise.

    On the other hand, note that the use of constant pragma can raise questions of whether the use of barewords is of concern in your code (which it may or may not be).

    The "good practice" regards the programming benefits of using constant (read-only) declarations for variables that should not be changing. Such practice generally improves the code substantially.