|Problems? Is your data what you think it is?|
Re: $_ vs. argument passingby Stevie-O (Friar)
|on Dec 22, 2004 at 20:48 UTC||Need Help??|
One of the reasons why the arg version is so much faster is because of a little-known feature of Perl: the arguments to functions are passed by-reference. That means when you use $_, you're actually referring to the constant 'foobar' which is embedded in the Perl bytecode.
On the other hand, your $_ = 'foobar' induces a string copy of 'foobar' every single time that statement is executed. Since calculating the length is easy, the additional overhead of the extra copying *really* stands out.
I added these two subs to the benchmark:
And reran it (dropping the time from 60s each to 10s each, because I'm far too impatient to wait six minutes for the test to rerun):
Note that they're still not on equal footing: the additional symbol table lookup needed to find the location of $_ *really* hurts. This is because the work needed to find $_ in the symbol table is far greater than the work needed to find the length of it (because the length is precomputed).
But if you're worried about performance, keep in mind that your slowest one executed in an average of 5.5 microseconds, which on a short-running script isn't terrible.