eduardo has asked for the wisdom of the Perl Monks concerning the following question:

let us say that I have some code that looks like this:
sub my_sub($) { ... do something EASY and fast ... } foreach my $i (0 .... $a_bazillion) { my_sub($some_value); }
if the code inside my_sub operates faster than the my_sub call itself, it's kind of stupid to keep it in a sub, i agree. but let us say that for reasons of software engineering and particular specifications, it is neccessary to keep that little piece of trivial code, in a sub (or a sub reference) is there a way to tell the perl interpreter to either: a) inline the sub (i know, evil C++ thing, it works!) or b) speed it up some OTHER way?

Replies are listed 'Best First'.
RE: method inlineing
by mikfire (Deacon) on May 26, 2000 at 23:20 UTC
    Yes, there is a way to get perl to inline the function, but only under certain circumstances. If you perldoc perlsub ( or visit the Library to read the Perl subroutines section) and search on Constant Functions, there is a very good explanation in there about how to set it up.

    Mik
    mikfire ( perlus bigotus maximus )

RE: method inlineing
by Shendal (Hermit) on May 26, 2000 at 23:05 UTC
    Assuming that what is inside &my_sub is optimized, I can't think of much you can do. According to my (limited) research, passing a scalar by reference doesn't typically buy you any speed. Unless, I suppose, the scalars are huge.

    You may consider something like the following, assuming that &my_sub returns a value:

    sub my_sub($) { ... do something EASY and fast ... return \$foo } foreach my $i (0 .. $a_bazillion) { $return_value = ${my_sub($some_value); }

    While I've never tried this personally, it may make a difference regarding performance. I suggest liberal use of use Benchmark; and see what helps.

    HTH!
Re: method inlineing
by jjhorner (Hermit) on May 26, 2000 at 22:49 UTC

    Are you sure that leaving it that way is a bad thing?

    Have you tried to Benchmark each way to see if it is really faster?

    If you want more optimized code, look at _Effect Perl Programming_ (written with the help of merlyn) or _Mastering Algorithms with Perl_. Both books provide new ways of doing things that most don't think of.

    I hope this helps.

    J. J. Horner

    Linux, Perl, Apache, Stronghold, Unix

    jhorner@knoxlug.org http://www.knoxlug.org