Lets take a look at the efficiency of using a sub vs. not using a sub. Efficiency is an important part of elegance, and so you should be aware of the performance differences when trying to find the most aesthetic way to code something.
Here is the code I used to benchmark. To give the best case, I've used reptile's function code.
use Benchmark;
$n = 1;
timethese( 0, {
'sub' => 'flipflop($n)',
'norm' => '$n = !($n)' } );
sub flipflop {
$_[0] = !($_[0])
}
And the output:
Benchmark: running norm, sub, each for at least 3 CPU seconds...
norm: 4 wallclock secs ( 3.24 usr + 0.00 sys = 3.24 CPU) @ 679799.69/s (n=2202551)
sub: 3 wallclock secs ( 3.16 usr + 0.00 sys = 3.16 CPU) @ 169643.35/s (n=536073)
And so in this case it is a whopping 4.007232836 times faster not to use a function call.
But, is reptile's code faster than raflach's? raflach's code is shorter, after all. But, it does have to return a value. Lets test it and see.
use Benchmark;
$n = 1;
timethese( 0, {
'sub' => '$n = flip($n)',
'norm' => '$n = !($n)' } );
sub flip { !($_[0]) }
and the results...
Benchmark: running norm, sub, each for at least 3 CPU seconds...
norm: 3 wallclock secs ( 3.17 usr + 0.00 sys = 3.17 CPU) @ 696554.57/s (n=2208078)
sub: 4 wallclock secs ( 3.26 usr + 0.00 sys = 3.26 CPU) @ 118730.98/s (n=387063)
So, ditching the sub and just flipping the value by hand is 5.866662349 times faster this time. Looks like having to return and adding is less efficient.
In most cases, I would highly recommend against using the refs passed to a function to alter those variables directly, but in this case I don't think there is any confusion generated.
Yes, I know that performance isn't everything.
note: these tests performed on an AMD K6-II/400 w/128 megs SDRAM, running linux 2.2.12. Your mileage may vary.
Paris Sinclair | 4a75737420416e6f74686572
pariss@efn.org | 205065726c204861636b6572
I wear my Geek Code on my finger.
|