Hack #80. Profile Your Program Size
Find out how much memory your program takes, and then trim it!
The difference between a Perl program and a natively compiled binary is far more than just program convenience. Although the Perl program can do far more with less source code, in memory, Perl's data structures and bookkeeping can take up more space than you might think. Size matters sometimes—even if you have plenty of memory (if you're not trying to optimize for shared memory in a child-forking application, for example), a program with good algorithms and not tied to IO or incoming requests can still run faster if it has fewer operations to perform.
One of the best optimizations of Perl programs is trimming the number of operations it has to perform. The less work it has to do, the better.
This isn't an argument for obfuscated or golfed code—just good profiling to find and trim the few fat spots left in a program.
The Hack
When Perl compiles a program, it builds an internal representation called the optree. This represents every single discrete operation in a program. Thus knowing how many opcodes there are in a program (or module) and the size of each opcode is necessary to know where to start optimizing.
The B::TerseSize module is
useful in this case.[15] It adds a size( ) method to all ops. More importantly, it gives you detailed information about the size of all symbols in a package if you call package_size( ).
To find the largest subroutine in a package and report on its opcodes, ...