Space Efficiency
Give variables the shortest scope possible so they don’t take up space when they aren’t needed.
Use
vecfor compact integer array storage if the integers are of fixed width. (Integers of variable width can be stored in a UTF-8 string.)Prefer numeric values over equivalent string values; they require less memory.
Use
substrto store constant-length strings in a longer string.Use the
Tie::SubstrHashmodule for very compact storage of a hash array if the key and value lengths are fixed.Use
_ _END_ _and theDATAfilehandle to avoid storing program data as both a string and an array.Prefer
eachtokeyswhere order doesn’t matter.Delete or
undefglobals that are no longer in use.Use some kind of DBM to store hashes on disk instead of inside the program.
Use temp files to store arrays.
Use pipes to offload processing to other tools. They clean up their memory use when they exit.
Avoid list operations and entire file slurps.
Avoid using
tr///. Eachtr///expression must store a sizable translation table.Don’t unroll your loops or inline your subroutines.
Use
File::Mapto read files if you don’t need to modify the data (and sometimes even if you do).Avoid recursion. Perl doesn’t have tail-call optimization since it’s a dynamic language. You should be able to convert those to an iterative approach, which is how languages with tail-call optimize recursion.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access