http://qs1969.pair.com?node_id=54003

BoredByPolitics has asked for the wisdom of the Perl Monks concerning the following question:

I asked a question in the CB earlier today regarding testing a string to check that it a) consisted of just one characeter, and b) that character was in the range A to Z.

I'd already come up with the regex /^[A..Z]$/ but I realised that there was probably a much more efficient way of doing it (especially seeing as it'll be happening 1000's of times in the code I am writing).

Corion suggested if (($str ge "A") && ($str le "Z")), while tilly suggested setting up a hash containing the values which I wanted to evaluate as true, then test with if (exists $chrs{$item}).

I decided this was a good time to learn how to use the Benchmark module, so this is what I ran to test all 3 -

use strict; my %tran_types; foreach ('A'..'Z') { $tran_types{$_} = "" }; my $test_char; timethese(10000000, { 'regex' => sub { $test_char = chr( int( rand 256 ) ); if ($test_char =~ /^[A..Z]$/) {} else {} }, 'comp' => sub { $test_char = chr( int( rand 256 ) ); if (($test_char ge "A") && ($test_char le "Z")) {} + else {} }, 'exist' => sub { $test_char = chr( int( rand 256 ) ); if (exists $tran_types{$test_char}) {} else {} }, });

I've no idea whether the above use of rand was a good idea or not, or if I needed to add the else on to the if (it'll be there in the production code). Here are the results -

Benchmark: timing 10000000 iterations of comp, exist, regex... comp: 56 wallclock secs (55.39 usr + 0.00 sys = 55.39 CPU) exist: 50 wallclock secs (49.34 usr + 0.00 sys = 49.34 CPU) regex: 79 wallclock secs (79.32 usr + 0.00 sys = 79.32 CPU)

Clearly tilly's suggestion is the winner, and I get to see first hand why regex's aren't always the best solution, even if they are quicker to type :-)

I don't suppose there's an even quicker solution ;-) ?

Pete - who's very grateful to tilly and Corion