use strict; use Benchmark qw(cmpthese); use constant NUM_OF_VARS => 10000; use constant NUM_OF_TESTS => 1000; my @names = (); # Meaningless, getting rid of warning *NULL = *NULL; open(NULL, '>/dev/null') or die "Couldn't open /dev/null: $!; stopped"; ## Initialize a bunch of variables to interpolate { no strict 'refs'; my $var_name = 'aa'; for ( 0 .. NUM_OF_VARS ) { $ {"Q::$var_name" } = "Name is '$var_name', number $_"; push(@names, "\$Q::$var_name"); $var_name++; } } # Build up two subroutine strings to eval my $list_print = "print NULL "; $list_print .= join(",\n", map( qq{'$_ is ', $_, "\\n"}, @names) ); $list_print .= ';'; my $build_print = "my \$string = '';\n"; foreach my $name (@names) { $build_print .= qq{\$string .= '$name is ';\n}; $build_print .= qq{\$string .= $name;\n}; $build_print .= qq{\$string .= "\\n";\n}; } $build_print .= "print NULL \$string;\n"; # Benchmark the subs cmpthese(NUM_OF_TESTS, { 'build_print' => $build_print, 'list_print' => $list_print, }); #### Benchmark: timing 1000 iterations of build_print, list_print... build_print: 120 wallclock secs (119.84 usr + 0.04 sys = 119.88 CPU) @ 8.34/s (n=1000) list_print: 92 wallclock secs (91.23 usr + 0.11 sys = 91.34 CPU) @ 10.95/s (n=1000) Rate build_print list_print build_print 8.34/s -- -24% list_print 10.9/s 31% --