I'm working ona small CPAN module, File::Find::Match, which allows one to write rules for finding and processing files, sort of like File::Find but with more control over recursion into directories and such.

Currently, before calling each "action" (code that is executed when a file matches a pattern, basically) I set $_ to the file name. However, as I'm writing this in a hybrid functional/OO style, I found I dislike using the global.

So, now I'm going to be passing the filename as the first argument to the coderef. I thought this would be slower, and I wanted to know how much slower, so I bench marked it:

#!/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); cmpthese(-60, { arg => sub { arg('foobar'); }, arg_shift => sub { arg_shift('foobar'); }, noarg => sub { $_ = 'foobar'; noarg(); }, noarg2 => sub { $_ = 'foobar'; noarg2(); }, }); sub arg { length $_[0] } sub arg_shift { length shift } sub noarg { length $_ } sub noarg2 { length }
The results of that (on Debian Sarge, perl 5.8.4 w/threads, on a 450mhz PII with 377MB of RAM) is:
Rate noarg noarg2 arg_shift arg noarg 181644/s -- -6% -45% -54% noarg2 193848/s 7% -- -41% -50% arg_shift 329166/s 81% 70% -- -16% arg 391348/s 115% 102% 19% --

So it appears accessing $_[0] is faster than accessing $_. And even shift() is faster than using $_.

So now all that is left is the usability. Is it much more of a pain to write actions using $_[0] than $_?

I'm also curious why passing an argument is faster than accessing $_. :)

Update: I should mention, File::Find::Match is being used to create a Make replacement that works recursively over many trees. Like the ttree script from Template Toolkit.


In reply to $_ vs. argument passing by Dylan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.