Performance

Perl lets you do just about whatever you want,and that includes things that may be slow or memory-intensive.Here's how to avoid some of these.

Use while to iterate over files,not for

Instead of slurping in all lines of a file and then working on the array with for,read in one line at a time with while.

These two loops are functionally the same:

  1. for ( <> ) {
  2. # do something
  3. }
  4.  
  5. while ( <> ) {
  6. # do something
  7. }

The difference is that the for reads the entire file into a temporary array, and the while reads one at a time. For small files this may not matter, but for larger ones it may eat up all your available memory.

Using while in this case is just good practice.


Want to contribute?

Submit a PR to github.com/petdance/perl101