原則ループ外宣言を使う派でしたが、実際の実行時間測ったこと無かったのでメモ
思っていたよりは実行時間に差が出た。
結論
ループ内で変数宣言する場合はループ外の場合の 1.5〜2倍 ぐらい時間がかかっていた。
perl version
perl -v
This is perl 5, version 24, subversion 1 (v5.24.1) built for darwin-2level
(with 1 registered patch, see perl -V for more detail)
使用したコード
test.pl
use strict;
use warnings;
use Time::HiRes;
my $NUM = 10000000;
my @array;
foreach (0...$NUM) {
push @array, int(rand(100));
}
my $start_time = Time::HiRes::time;
# declare out of loop
my $count1;
for (@array) {
$count1 = $_ * 10;
}
printf("declare out of loop \t: %0.5f\n", Time::HiRes::time - $start_time);
# declare in loop
$start_time = Time::HiRes::time;
for (@array) {
my $count2 = $_ * 10;
}
printf("declare in loop \t: %0.5f\n", Time::HiRes::time - $start_time);
結果(3回ずつ)
$NUM=10000
perl test.pl
declare out of loop : 0.00037
declare in loop : 0.00080
perl test.pl
declare out of loop : 0.00045
declare in loop : 0.00075
perl test.pl
declare out of loop : 0.00046
declare in loop : 0.00083
$NUM=10000000
perl test.pl
declare out of loop : 0.38353
declare in loop : 0.68609
perl test.pl
declare out of loop : 0.45468
declare in loop : 0.65201
perl test.pl
declare out of loop : 0.40082
declare in loop : 0.64218