In-Memory File
参考:http://blog.livedoor.jp/dankogai/archives/50681645.html
Perl5.8以降からIn-Memory Fileという機能が使えるんだそうです。
#!/usr/bin/perl use strict; use warnings; use Devel::Size qw(total_size); my @array = (0x21..0x7e); my $memfile; open my $wfh, '>', \$memfile or die $!; print $wfh chr($_) for @array; close($wfh); open my $rfh,'<', \$memfile or die $!; #print while(<$rfh>); close $rfh; print "\@array size is ". total_size(\@array) . " Byte.\n"; print "\$memfile size is ". total_size(\$memfile) . " Byte.\n";
実行結果は以下です。
@array size is 2316 Byte. $memfile size is 148 Byte.
open関数の通常ならファイル名を渡すところを、スカラー変数のリファレンスを渡してます。
これが、In-Mmeory Fileのオープンの仕方ですね。
メモリ使用量がArrayに比べ、15分の1になってます。つよい。
しかし、Speedは遅くなる。
#!/usr/bin/perl use strict; use warnings; use Benchmark qw/timethese cmpthese/; cmpthese(timethese( 0, { array => sub { my @array = (); push @array, $_ for ( 0 .. 0xff ); for ( 0 .. 0xff ) { $array[$_] != $_ and die; } }, memfile => sub { my $memfile = ''; open my $wfh, '>', \$memfile or die; print $wfh $_, "\n" for ( 0 .. 0xff ); close $wfh; open my $rfh, '<', \$memfile or die; for ( 0 .. 0xff ) { my $line = <$rfh>; $_ == $line or die; } close $rfh; } } ));
実行結果は以下です。
Benchmark: running array, memfile for at least 3 CPU seconds... array: 3 wallclock secs ( 3.16 usr + 0.00 sys = 3.16 CPU) @ 2236.05/s (n=7075) memfile: 3 wallclock secs ( 3.18 usr + 0.00 sys = 3.18 CPU) @ 709.82/s (n=2257) Rate memfile array memfile 710/s -- -68% array 2236/s 215% --
処理速度は1/3程度のようです。