in reply to The best way to use constants
Is using constants slower than using variablesConsidering that Perl doesn't have constants, the question isn't clear. It will depend on what you consider a constant. Many people consider a variable in all caps to be a constant. That of course is as fast as using constants.
Others use "use constant" or tiny subs with an empty prototype returning a literal as constants. Are they faster than variables? Well, that depends. If it's just fetching a value (read access), yes, then they are faster as the fetch can be done at compile time. But such constants lack a sigil. So you cannot easily interpolate them. Hence, you might write:
instead ofprintf "The value is %d.\n", CONSTANT;
The former means parsing a format, and substituting. That may very well be slower than the interpolation.print "The value is $CONSTANT.\n";
Now, you are using methods as constants. I haven't benchmarked it, but I'd be quite surprised if that wasn't the slowest solution of the three (variable, empty prototype sub, method).
Personally, I prefer variable. In all caps. Speed difference isn't an issue for me. Variables interpolate; subs and methods don't. If I want to trap a possible assignment to such a variable, I use Readonly. But usually, I do not care. If someone wants to assign to something that's supposed to constant, it's their own responsibility. Who am I to stop them?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: The best way to use constants
by almut (Canon) on Apr 02, 2009 at 19:29 UTC | |
by saurabh.hirani (Beadle) on Apr 03, 2009 at 06:13 UTC |