I decided to benchmark this and see what the difference was. Here is the script...
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw(:all);
use Params::Validate qw(:all);
sub ParamsValidateAssert {
my ($test) = validate_pos( @_,
{
type => SCALAR,
callbacks => { 'must be less than 50' => s
+ub { $_[0] < 50 }},
}
);
return $test;
}
sub OrAssert {
my ($test) = @_;
($test < 50) || die "Test is wrong";
return $test;
}
my @nums = map { ((rand() * 100) % 50) } (0 .. 100);
cmpthese(10_000, {
'ParamsValidateAssert' => sub { eval { ParamsValidateAssert($_) }
+for (@nums) },
'OrAssert' => sub { eval { OrAssert($_) }
+for (@nums) },
});
Here are the results...
Benchmark: timing 10000 iterations of OrAssert, ParamsValidateAssert..
+.
OrAssert: 8 wallclock secs ( 7.02 usr + 0.01 sys = 7.03 CPU) @ 14
+22.48/s (n=10000)
ParamsValidateAssert: 97 wallclock secs (87.88 usr + 0.38 sys = 88.26
+ CPU) @ 113.30/s (n=10000)
Rate ParamsValidateAssert OrAssert
ParamsValidateAssert 113/s -- -92%
OrAssert 1422/s 1155% --
It is almost 100% faster to use OR. Again, as I said, I think my style is less verbose and more readable so I favor it becuase of that as well.
But as water points out below, it should not completely be about the speed. I am sure that Params::Validate has a number of wheels I would not want want to have to re-invent when I hand-code OR based assertions. Looking over the docs for Params::Validate, I see where this could really be a useful tool for data validation, not just of subroutine parameters, but of web queries and such. As you say it can be quite declarative and I can see how you could build some very sophisticated data validation with it. However, I do think it is overkill for subroutine params and post/pre-condition checking.
-
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.