Recently I came across the idiom of using scalar() to get a head count of the entries in an array, up until then I'd always used '$#array+1', interested to see if there was a good reason why I should use this new idiom, I did a bit of benchmarking with the included script and got the following results
Out put from first run: Benchmark: timing 125000 iterations of addition_to_$#test, scalar_derived... addition_to_$#test: 1 secs ( 2.15 usr 0.00 sys = 2.15 cpu) scalar_derived: 2 secs ( 1.18 usr 0.00 sys = 1.18 cpu) Benchmark: timing 350000 iterations of addition_to_$#test, scalar_derived... addition_to_$#test: 5 secs ( 6.00 usr 0.00 sys = 6.00 cpu) scalar_derived: 2 secs ( 2.78 usr 0.00 sys = 2.78 cpu) Being impressed by the fact the scalar derived method didn't change at all even though the iterations were doubled, I got to wondering about the sudden leap in the time required by the addition_to_$#test method and if I was ever going to require a script to carry out this operation 350,000 times to merit the extra overhead incurred by using scalar() and ran the script again: Out put from second run: Benchmark: timing 125000 iterations of addition_to_$#test, scalar_derived... addition_to_$#test: 1 secs ( 1.73 usr 0.00 sys = 1.73 cpu) scalar_derived: 2 secs ( 1.28 usr 0.00 sys = 1.28 cpu) Benchmark: timing 350000 iterations of addition_to_$#test, scalar_derived... addition_to_$#test: 5 secs ( 4.80 usr 0.00 sys = 4.80 cpu) scalar_derived: 4 secs ( 3.73 usr 0.00 sys = 3.73 cpu) Anyone got a clue as to why the second run sees the values for the scalar_derived method has almost doubled? Is this a memory leak in MacPerl or something else? #!perl-w use Benchmark; @test = (1, 2, 3,4,5,6,7,); # Use Perl code in strings... timethese(125000, { 'scalar_derived' => sub {$number = scalar (@test);}, 'addition_to_$#test' => sub {$number =$#test+1;}, }); timethese(350000, { 'scalar_derived' => sub {$number = scalar (@test);}, 'addition_to_$#test' => sub {$number =$#test+1;}, }); __END__