in reply to Re: Constant subroutines thoughts
in thread Constant subroutines thoughts
I was not advocating for usage of "almost constant subs" as opposed of usual subs. But I'll summarize this at the end of a message.
Okay, Now let us cover more details on things that you did not understood.
First, how I do 'deparse' and why I see that something was optimized away. You can read how to use deparse using command perldoc B::Deparse with many good examples.
Note how you can 'deparse' your snippet, or may be entire script:
Okay. But what goes on when we see following:C:\>perl -MO=Deparse -e "print 'this' if $x" print 'this' if $x; -e syntax OK
Those question marks are here because entire 'print' statement goes away. When you enter command perldoc B::Deparse again, there is an explanation there about those questions marks.C:\>perl -MO=Deparse -e "print 'this' if 0" '???'; -e syntax OK
As an additional demonstration try to analyze following:
You see? That constant subroutine never called, instead it's value inlined everywhere, thus giving us an optimization.D:\>perl -MO=Deparse -e "sub MY_CONST(){'bla-bla'};$a=MY_CONST;print M +Y_CONST;" sub MY_CONST () { 'bla-bla'; } $a = 'bla-bla'; print 'bla-bla'; -e syntax OK
Everywhere our "almost constant sub" is called, thus slowing down things a bit.D:\>perl -MO=Deparse -e "sub MY_CONST{'bla-bla'};$a=MY_CONST;print MY_ +CONST;" sub MY_CONST { 'bla-bla'; } $a = MY_CONST(); print MY_CONST(); -e syntax OK
Good.
Now why I said 'Not that good anymore' in my initial message:
Because in first case my program was a bit slower and bigger, because everywhere all my statements 'if DEBUG' were recalculataed again, and again, and again, whereas in second case they were just thrown away during compilation stage!C:\>perl -MO=Deparse -we "sub DEBUG{0}print 'this' if DEBUG;" sub DEBUG { 0; } print 'this' if DEBUG ; -e syntax OK C:\>perl -MO=Deparse -we "sub DEBUG(){0}print 'this' if DEBUG;" sub DEBUG () { 0; } '???'; -e syntax OK
After I explained more details, let me explain why I was not advocating for either of them.
Okay, that was not my goal.
Additionally, may be sometimes module authors intentinally want to leave constant sub to
be overridable in sub-class, or something like this.
But in most cases (like in family of Win32::* modules) they probably should be corrected to use really constant subroutines, so we'll gain speed and probably memory a bit.
Let me know if I still did not covered something.
Good luck,
Courage, the Cowardly Dog.
PS. Something fishy is going on there, or my name is Vadim Konovalov. And it's not.
|
|---|