2016-05-17T13:26:46 reneeIm Schleifenkopf oder innerhalb der Schleife?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
use warnings; use strict; use Benchmark "timethese"; my $count = 5000; my @array = qw( a b c ); my $glbArraySize = scalar( @array ); timethese( 10000, { "scalarSavedGlobally" => sub { for ( 1 .. $count ) { my $foo = 1 if $glbArraySize == $_; } }, "scalarSavedLocally" => sub { my $arraySize = scalar( @array ); for ( 1 .. $count ) { my $foo = 1 if $arraySize == $_; } }, "scalarNotSaved" => sub { for ( 1 .. $count ) { my $foo = 1 if scalar( @array ) == $_; } } } );
1
2
3
4
Benchmark: timing 10000 iterations of scalarNotSaved, scalarSavedGlobally, scalarSavedLocally...
scalarNotSaved: 9 wallclock secs ( 9.14 usr + 0.00 sys = 9.14 CPU) @ 1093.85/s (n=10000)
scalarSavedGlobally: 6 wallclock secs ( 5.63 usr + 0.00 sys = 5.63 CPU) @ 1775.57/s (n=10000)
scalarSavedLocally: 6 wallclock secs ( 5.68 usr + 0.00 sys = 5.68 CPU) @ 1761.18/s (n=10000)
1
2
3
4
5
Rate scalarNotSaved directly_compared scalarSavedGlobally scalarSavedLocally
scalarNotSaved 1060/s -- -0% -39% -40%
directly_compared 1062/s 0% -- -39% -40%
scalarSavedGlobally 1745/s 65% 64% -- -1%
scalarSavedLocally 1757/s 66% 66% 1% --
my $foo = 1 if $arraySize == $_;
perldoc perlsyn...
NOTE: The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ... ) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.
...