in reply to Most efficient way to print a file?

I'm returning it in a function call...

In case the string is huge and you want to avoid some temporary memory allocation (which could push up the peak memory usage of the program), you could return a reference to the scalar:

#!/usr/bin/perl sub mem { print "$_[0]:\n"; system "/bin/ps", "-osize,vsize", $$; } sub foo { mem(0); my $data; $data .= "xxxxxxxxxx" for 1..1_000_000; mem(1); return \$data; # return reference } my $r = foo(); # then get at the data using $$r mem(2); __END__ $ ./880173.pl 0: SZ VSZ 612 19804 1: SZ VSZ 10468 29660 2: SZ VSZ 10468 29660

Using the same snippet, but with return $data, you'd get:

0: SZ VSZ 612 19804 1: SZ VSZ 10468 29660 2: SZ VSZ 20236 39428

As you can see, the process size has grown additionally by about the size of $data.

Whether this really saves anything overall depends on what else the program is doing to actually print the string, etc.

Replies are listed 'Best First'.
Re^2: Most efficient way to print a file?
by DreamT (Pilgrim) on Jan 03, 2011 at 13:52 UTC
    Ok, ill try that! But, what is the most efficient way to open the file?
      Really, does it matter? It's like asking the most efficient way to close your car door to minimize the time of your Miami to New York road trip.
        There is a lot of files that's going to be opened a lot of times, so I just want to be sure that this link in the chain is optimal

        The thing I'm most concerned with is the best way to put the file in the variable. I do it in a clumsy way today.
        open(FILE, "<test.txt"); @myfile = <FILE>; close(FILE); foreach $myrow (@myfile) { $result .= $myrow; } return $result;
        I just want to do that in a better way :-)

      As the Anonymous Monk already said, you can use open or sysopen, but there probably won't be much difference, as most likely the majority of the time is spent in the underlying system call open(2), i.e. outside of the Perl program/in the kernel.

      If you really want to know: Benchmark.