But it turns out that your approach isn't as slow as I thought it would be. It's still slower than using an array, but not terribly.
Comparing the strftime version isn't totally fair, since it's not a simple "month->string" converter, but requires a localtime list. But as others have pointed out, it will do locales correctly.Benchmark: running inlineArrayLookup, preBuiltArrayLookup, strftimeLoo +kup, substrLookup, each for at least 2 CPU seconds... inlineArrayLookup: 2 wallclock secs ( 2.12 usr + -0.01 sys = 2.11 CP +U) @ 543540.28/s (n=1146870) preBuiltArrayLookup: 1 wallclock secs ( 2.04 usr + -0.01 sys = 2.03 +CPU) @ 588310.34/s (n=1194270) strftimeLookup: 3 wallclock secs ( 1.76 usr + 0.37 sys = 2.13 CPU) +@ 216666.20/s (n=461499) substrLookup: 2 wallclock secs ( 2.09 usr + 0.00 sys = 2.09 CPU) @ +465374.16/s (n=972632) Rate strftimeLookup substrLookup inlineArrayLo +okup preBuiltArrayLookup strftimeLookup 216666/s -- -53% +-60% -63% substrLookup 465374/s 115% -- +-14% -21% inlineArrayLookup 543540/s 151% 17% + -- -8% preBuiltArrayLookup 588310/s 172% 26% + 8% --
#!/usr/bin/perl -w use strict; use Benchmark qw(cmpthese); use POSIX 'strftime'; my @months=qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); sub getMonthNumber { return int(rand(12)); } sub preBuiltArrayLookup { return $months[getMonthNumber()]; } sub inlineArrayLookup { return qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)[getMont +hNumber()]; } sub substrLookup { return substr('JanFebMarAprMayJunJulAugSepOctNovDec',getMonthNumbe +r()*3,3); } # so as to not penalize strftime with localtime call my @fixedLocaltime=localtime; sub strftimeLookup { return strftime "%m",@fixedLocaltime; } cmpthese(-2, { 'preBuiltArrayLookup' => \&preBuiltArrayLookup, 'inlineArrayLookup' => \&inlineArrayLookup, 'substrLookup' => \&substrLookup, 'strftimeLookup' => \&strftimeLookup, } );
Edit: Added strftime variant which I had overlooked.
Edit by tye, change PRE to CODE around long lines
In reply to Re: Re: Replacing $mon with Jan, Feb, Mar by regex or other means
by RMGir
in thread Replacing $mon with Jan, Feb, Mar by regex or other means
by jonnyfolk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |