http://qs321.pair.com?node_id=1078544


in reply to Re^4: Given When Syntax
in thread Given When Syntax

You're using a constant input which starts with a "3" though, which unfairly penalizes test1 and test2 (it's the final situation they check for). For inputs starting with a "1", test3 is still the fastest, but the difference between it and the other tests is much smaller.

Yes, you are absolutely right, tobyink, I did unfairly penalize test1 and test2, and I did it consciously and voluntarily, because, in a real situation, I would assume that the first digit in the input can take any value between 1 and 9 (and possibly 0), so that having a match at the third value actually gives an unfair advantage to test1 and test2. Having said that, with three possible values, matching at the second value should be fair if values are more or less equally distributed. Changing my benchmark test to:

cmpthese( -1, { test_1 => sub {test1("2.01.000")}, test_2 => sub {test2("2.01.000")}, test_3 => sub {test3("2.01.000")}, } )
I obtain the following result:
$ perl test_if.pl Rate test_1 test_2 test_3 test_1 1451608/s -- -8% -46% test_2 1578202/s 9% -- -41% test_3 2667353/s 84% 69% --
which still shows a very clearcut advantage to the array solution.

As for using

cmpthese(-1, { test_1 => q{ test1("3.01.000") }, test_2 => q{ test2("3.01.000") }, test_3 => q{ test3("3.01.000") }, });
I was not aware of the possibility of doing it this way, thank you for the information, I'll investigate this further. I doubt, though, that it really makes a huge difference, a factor of two between one solution and the others is not exactly what I would call micro-optimization.

Replies are listed 'Best First'.
Re^6: Given When Syntax
by tobyink (Canon) on Mar 17, 2014 at 17:29 UTC

    I think any improvements - even a ten-fold speed-up - to a sub that can be run 1.5 million times a second counts as a micro-optimization. ;-)

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name