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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.