in reply to Re: Reading from file, not to memory
in thread Reading from file, not to memory
You have to be careful here, because you are doing exactly the same thing. The foreach statement is also accessing <FB> in array context and is reading the whole file into an anonymous array and then iterating over it. You have to use a while loop for this to work correctly.
Try out the following bit of code to test this:
use Benchmark; timethese(1, { 'Trial1 While' => sub { open (FILE, "file2") or die "Can't open file: $!\n"; while (<FILE>) { last; # read one line and exit } close FILE; }, 'Trial2 Foreach' => sub { open (FILE, "file1") or die "Can't open file: $!\n"; foreach my $line (<FILE>) { last; # read one line and exit } close FILE; }, });
Make sure that file1 and file2 are identical (I used two files so that we know there is no caching going on), and that they are large text files. I got the following results with 2 50Meg files:
Benchmark: timing 1 iterations of Trial1 While, Trial2 Foreach... Trial1 While: 0 wallclock secs ( 0.00 usr + 0.00 sys = 0.00 CPU) Trial2 Foreach: 17 wallclock secs (10.77 usr + 1.56 sys = 12.33 CPU) +@ 0.08/s (n=1)
|
|---|