我想知道基于互联网上的许多书籍,如果$ _是通过数组迭代的更快的方式(没有实例化新变量),但不知怎的,我总是得到不同的结果。这是性能代码测试:
#!/usr/bin/perl
use Time::HiRes qw(time);
use strict;
use warnings;
# $_ is a default argument for many operators, and also for some control structures.
my $test_array = [1..1000000];
my $number_of_tests = 100;
my $dollar_wins = 0;
my $dollar_wins_sum = 0;
for (my $i = 1; $i <= $number_of_tests; $i++) {
my $odd_void_array = [];
my $start_time_1 = time();
foreach my $item (@{$test_array}) {
if ($item % 2 == 1) {
push (@{$odd_void_array}, $item);
}
}
foreach my $item_odd (@{$odd_void_array}) {
}
my $end_time_1 = time();
$odd_void_array = [];
my $start_time_2 = time();
foreach (@{$test_array}) {
if ($_ % 2 == 1) {
push (@{$odd_void_array}, $_);
}
}
foreach (@{$odd_void_array}) {
}
my $end_time_2 = time();
my $diff = ($end_time_1-$start_time_1) - ($end_time_2-$start_time_2);
if ($diff > 0) {
$dollar_wins ++;
$dollar_wins_sum += $diff;
print "Dollar won ($dollar_wins out of $i) with diff $diff \n";
}
}
print "=================================\n";
print "When using dollar underscore, execution was faster in $dollar_wins cases (".(($dollar_wins/$number_of_tests)*100)."%), with average difference of ".($dollar_wins_sum/$dollar_wins)."\n";
所以,我有两次迭代(一次分配给我的$ item,另一次没有)。我得到的主要是,在大约20-30%的情况下,$ _的迭代速度更快。
如果没有新变量更快,不应该迭代吗?
答案 0 :(得分:12)
您并不是真正使用不同变量对迭代进行基准测试。
让我们采取这个更好的测试,实际上对您声称要进行基准测试的方法进行基准测试:
use strict;
use warnings;
use Benchmark ':hireswallclock', 'cmpthese';
my @numbers = 1..100_000;
cmpthese -3, {
'$_' => sub {
for (@numbers) {
1;
}
},
'my $x' => sub {
for my $x (@numbers) {
1;
}
},
'$x' => sub {
my $x;
for $x (@numbers) {
1;
}
},
}
结果:
Rate $_ my $x $x
$_ 107/s -- -0% -0%
my $x 107/s 0% -- -0%
$x 108/s 0% 0% --
所以他们在我的测试系统上同样快(为i686-linux-thread-multi-64int构建的perl 5.18.2)。
我怀疑使用 $_
比词法略慢,因为它是一个全局变量。但是,迭代的速度是等效的。的确,修改基准......
use strict;
use warnings;
use Benchmark ':hireswallclock', 'cmpthese';
my @numbers = 1..100_000;
cmpthese -3, {
'$_' => sub {
for (@numbers) {
$_ % 2 == 0;
}
},
'my $x' => sub {
for my $x (@numbers) {
$x % 2 == 0;
}
},
'$x' => sub {
my $x;
for $x (@numbers) {
$x % 2 == 0;
}
},
}
...给出
Rate $_ $x my $x
$_ 40.3/s -- -1% -6%
$x 40.6/s 1% -- -5%
my $x 42.9/s 7% 6% --
但效果仍然太小,无法得出任何可靠的结论。