why are function calls in Perl loops so slow?

前端 未结 4 1579
无人共我
无人共我 2021-02-02 15:18

I was writing a file parser in Perl, so had to loop through file. File consists of fixed length records and I wanted to make a separate function that parses given record and cal

4条回答
  •  独厮守ぢ
    2021-02-02 15:20

    If your sub has no arguments and is a constant as in your example, you can get a major speed-up by using an empty prototype "()" in the sub declaration:

    sub get_string() {
        return sprintf(“%s\n”, ‘abc’);
    }
    

    However this is probably a special case for your example that do not match your real case. This is just to show you the dangers of benchmarks.

    You'll learn this tip and many others by reading perlsub.

    Here is a benchmark:

    use strict;
    use warnings;
    use Benchmark qw(cmpthese);
    
    sub just_return { return }
    sub get_string  { sprintf "%s\n", 'abc' }
    sub get_string_with_proto()  { sprintf "%s\n", 'abc' }
    
    my %methods = (
        direct      => sub { my $s = sprintf "%s\n", 'abc' },
        function    => sub { my $s = get_string()          },
        just_return => sub { my $s = just_return()         },
        function_with_proto => sub { my $s = get_string_with_proto() },
    );
    
    cmpthese(-2, \%methods);
    

    and its result:

                              Rate function just_return   direct function_with_proto
    function             1488987/s       --        -65%     -90%                -90%
    just_return          4285454/s     188%          --     -70%                -71%
    direct              14210565/s     854%        232%       --                 -5%
    function_with_proto 15018312/s     909%        250%       6%                  --
    

提交回复
热议问题