Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^2: Being more Assert-ive with Perl

by stvn (Monsignor)
on Sep 18, 2004 at 15:31 UTC ( [id://391996]=note: print w/replies, xml ) Need Help??


in reply to Re: Being more Assert-ive with Perl
in thread Being more Assert-ive with Perl

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.

-stvn

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://391996]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-20 01:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found