Dylan has asked for the wisdom of the Perl Monks concerning the following question:
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:
The results of that (on Debian Sarge, perl 5.8.4 w/threads, on a 450mhz PII with 377MB of RAM) is:#!/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 }
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: $_ vs. argument passing
by Stevie-O (Friar) on Dec 22, 2004 at 20:48 UTC | |
|
Re: $_ vs. argument passing
by chromatic (Archbishop) on Dec 22, 2004 at 19:54 UTC | |
by Dylan (Monk) on Dec 22, 2004 at 19:56 UTC | |
|
Re: $_ vs. argument passing
by revdiablo (Prior) on Dec 22, 2004 at 19:47 UTC | |
by Dylan (Monk) on Dec 22, 2004 at 19:53 UTC | |
by revdiablo (Prior) on Dec 22, 2004 at 20:44 UTC | |
by Dylan (Monk) on Dec 22, 2004 at 21:22 UTC | |
|
Re: $_ vs. argument passing
by bgreenlee (Friar) on Dec 22, 2004 at 19:56 UTC | |
by Dylan (Monk) on Dec 22, 2004 at 19:58 UTC |