File: //usr/local/share/man/man3/Type::Tiny::Manual::Optimization.3pm
.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{\
. if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{\
. nr % 0
. nr F 2
. \}
. \}
.\}
.rr rF
.\" ========================================================================
.\"
.IX Title "Type::Tiny::Manual::Optimization 3"
.TH Type::Tiny::Manual::Optimization 3 "2021-07-31" "perl v5.26.3" "User Contributed Perl Documentation"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
Type::Tiny::Manual::Optimization \- squeeze the most out of your CPU
.SH "MANUAL"
.IX Header "MANUAL"
Type::Tiny is written with efficiency in mind, but there are techniques
you can use to get the best performance out of it.
.SS "\s-1XS\s0"
.IX Subsection "XS"
The simplest thing you can do to increase performance of many of
the built-in type constraints is to install Type::Tiny::XS, a
set of ultra-fast type constraint checks implemented in C.
.PP
Type::Tiny will attempt to load Type::Tiny::XS and use its
type checks. If Type::Tiny::XS is not available, it will then
try to use Mouse \fIif it is already loaded\fR, but Type::Tiny
won't attempt to load Mouse for you.
.PP
Certain type constraints can also be accelerated if you have
Ref::Util::XS installed.
.PP
\fITypes that can be accelerated by Type::Tiny::XS\fR
.IX Subsection "Types that can be accelerated by Type::Tiny::XS"
.PP
The following simple type constraints from Types::Standard will
be accelerated by Type::Tiny::XS: \fBAny\fR, \fBArrayRef\fR, \fBBool\fR,
\&\fBClassName\fR, \fBCodeRef\fR, \fBDefined\fR, \fBFileHandle\fR, \fBGlobRef\fR,
\&\fBHashRef\fR, \fBInt\fR, \fBItem\fR, \fBObject\fR, \fBMap\fR, \fBRef\fR, \fBScalarRef\fR,
\&\fBStr\fR, \fBTuple\fR, \fBUndef\fR, and \fBValue\fR. (Note that \fBNum\fR and
\&\fBRegexpRef\fR are \fInot\fR on that list.)
.PP
The parameterized form of \fBRef\fR cannot be accelerated.
.PP
The parameterized forms of \fBArrayRef\fR, \fBHashRef\fR, and \fBMap\fR can be
accelerated only if their parameters are.
.PP
The parameterized form of \fBTuple\fR can be accelerated if its
parameters are, it has no \fBOptional\fR components, and it does not use
\&\f(CW\*(C`slurpy\*(C'\fR.
.PP
Certain type constraints may benefit partially from Type::Tiny::XS.
For example, \fBRoleName\fR inherits from \fBClassName\fR, so part of the
type check will be conducted by Type::Tiny::XS.
.PP
The parameterized \fBInstanceOf\fR, \fBHasMethods\fR, and \fBEnum\fR type
constraints will be accelerated. So will Type::Tiny::Class,
Type::Tiny::Duck, and Type::Tiny::Enum objects.
.PP
The \fBPositiveInt\fR and \fBPositiveOrZeroInt\fR type constraints from
Types::Common::Numeric will be accelerated, as will the
\&\fBNonEmptyStr\fR type constraint from Types::Common::String.
.PP
The \fBStringLike\fR, \fBCodeLike\fR, \fBHashLike\fR, and \fBArrayLike\fR types
from Types::TypeTiny will be accelerated, but parameterized
\&\fBHashLike\fR and \fBArrayLike\fR will not.
.PP
Type::Tiny::Union and Type::Tiny::Intersection will also be
accelerated if their constituent type constraints are.
.PP
\fITypes that can be accelerated by Mouse\fR
.IX Subsection "Types that can be accelerated by Mouse"
.PP
The following simple type constraints from Types::Standard will
be accelerated by Type::Tiny::XS: \fBAny\fR, \fBArrayRef\fR, \fBBool\fR,
\&\fBClassName\fR, \fBCodeRef\fR, \fBDefined\fR, \fBFileHandle\fR, \fBGlobRef\fR,
\&\fBHashRef\fR, \fBRef\fR, \fBScalarRef\fR, \fBStr\fR, \fBUndef\fR, and \fBValue\fR.
(Note that \fBItem\fR, \fBNum\fR, \fBInt\fR, \fBObject\fR, and \fBRegexpRef\fR
are \fInot\fR on that list.)
.PP
The parameterized form of \fBRef\fR cannot be accelerated.
.PP
The parameterized forms of \fBArrayRef\fR and \fBHashRef\fR can be
accelerated only if their parameters are.
.PP
Certain type constraints may benefit partially from Mouse. For
example, \fBRoleName\fR inherits from \fBClassName\fR, so part of the
type check will be conducted by Mouse.
.PP
The parameterized \fBInstanceOf\fR and \fBHasMethods\fR type constraints
will be accelerated. So will Type::Tiny::Class and
Type::Tiny::Duck objects.
.SS "Inlining Type Constraints"
.IX Subsection "Inlining Type Constraints"
In the case of a type constraint like this:
.PP
.Vb 1
\& my $type = Int\->where(sub { $_ >= 0 });
.Ve
.PP
Type::Tiny will need to call one sub to verify a value meets the \fBInt\fR
type constraint, and your coderef to check that the value is above zero.
.PP
Sub calls in Perl are relatively expensive in terms of memory and \s-1CPU\s0
usage, so it would be good if it could be done all in one sub call.
.PP
The \fBInt\fR type constraint knows how to create a string of Perl code
that checks an integer. It's something like the following. (It's actually
more complicated, but this is close enough as an example.)
.PP
.Vb 1
\& $_ =~ /^\-?[0\-9]+$/
.Ve
.PP
If you provide your check as a string instead of a coderef, like this:
.PP
.Vb 1
\& my $type = Int\->where(q{ $_ >= 0 });
.Ve
.PP
Then Type::Tiny will be able to combine them into one string:
.PP
.Vb 1
\& ( $_ =~ /^\-?[0\-9]+$/ ) && ( $_ >= 0 )
.Ve
.PP
So Type::Tiny will be able to check values in one sub call. Providing
constraints as strings is a really simple and easy way of optimizing
type checks.
.PP
But it can be made even more efficient. Type::Tiny needs to localize
\&\f(CW$_\fR and copy the value into it for the above check. If you're
checking \fBArrayRef[$type]\fR this will be done for each element of
the array. Things could be made more efficient if Type::Tiny were able
to directly check:
.PP
.Vb 1
\& ( $arrayref\->[$i] =~ /^\-?[0\-9]+$/ ) && ( $arrayref\->[$i] >= 0 )
.Ve
.PP
This can be done by providing an inlining sub. The sub is given a
variable name and can use that in the string of code it generates.
.PP
.Vb 11
\& my $type = Type::Tiny\->new(
\& parent => Int,
\& inlined => sub {
\& my ($self, $varname) = @_;
\& return sprintf(
\& \*(Aq(%s) && ( %s >= 0 )\*(Aq,
\& $self\->parent\->inline_check($varname),
\& $varname,
\& );
\& }
\& );
.Ve
.PP
Because it's pretty common to want to call your parent's inline check and
\&\f(CW\*(C`&&\*(C'\fR your own string with it, Type::Tiny provides a shortcut for this.
Just return a list of strings to smush together with \f(CW\*(C`&&\*(C'\fR, and if the
first one is \f(CW\*(C`undef\*(C'\fR, Type::Tiny will fill in the blank with the parent
type check.
.PP
.Vb 10
\& my $type = Type::Tiny\->new(
\& parent => Int,
\& inlined => sub {
\& my ($self, $varname) = @_;
\& return (
\& undef,
\& sprintf(\*(Aq%s >= 0\*(Aq, $varname),
\& );
\& }
\& );
.Ve
.PP
There is one further optimization which can be applied to this particular
case. You'll note that we're checking the string matches \f(CW\*(C`/^\-?[0\-9+]$/\*(C'\fR
and then checking it's greater than or equal to zero. But a non-negative
integer won't ever start with a minus sign, so we could inline the check to
something like:
.PP
.Vb 1
\& $_ =~ /^[0\-9]+$/
.Ve
.PP
While an inlined check \fIcan\fR call its parent type check, it is not required
to.
.PP
.Vb 7
\& my $type = Type::Tiny\->new(
\& parent => Int,
\& inlined => sub {
\& my ($self, $varname) = @_;
\& return sprintf(\*(Aq%s =~ /^[0\-9]+$/\*(Aq, $varname);
\& }
\& );
.Ve
.PP
If you opt not to call the parent type check, then you need to ensure your
own check is at least as rigorous.
.SS "Inlining Coercions"
.IX Subsection "Inlining Coercions"
Moo is the only object-oriented programming toolkit that fully supports
coercions being inlined, but even for Moose and Mouse, providing coercions
as strings can help Type::Tiny optimize its coercion features.
.PP
For Moo, if you want your coercion to be inlinable, all the types you're
coercing from and to need to be inlinable, plus the coercion needs to be
given as a string of Perl code.
.SS "Common Sense"
.IX Subsection "Common Sense"
The \fBHashRef[ArrayRef]\fR type constraint can probably be checked
faster than \fBHashRef[ArrayRef[Num]]\fR. If you find yourself using
very complex and slow type constraints, you should consider switching
to simpler and faster ones. (Though this means you have to place a
little more trust in your caller to not supply you with bad data.)
.PP
(A counter-intuitive exception to this: even though \fBInt\fR is more
restrictive than \fBNum\fR, in most circumstances \fBInt\fR checks will run
faster.)
.SS "Devel::StrictMode"
.IX Subsection "Devel::StrictMode"
One possibility is to use strict type checks when you're running your
release tests, and faster, more permissive type checks at other times.
Devel::StrictMode can make this easier.
.PP
This provides a \f(CW\*(C`STRICT\*(C'\fR constant that indicates whether your code is
operating in \*(L"strict mode\*(R" based on certain environment variables.
.PP
\fIAttributes\fR
.IX Subsection "Attributes"
.PP
.Vb 2
\& use Types::Standard qw( ArrayRef Num );
\& use Devel::StrictMode qw( STRICT );
\&
\& has numbers => (
\& is => \*(Aqro\*(Aq,
\& isa => STRICT ? ArrayRef[Num] : ArrayRef,
\& default => sub { [] },
\& );
.Ve
.PP
It is inadvisible to do this on attributes that have coercions because
it can lead to inconsistent and unpredictable behaviour.
.PP
\fIType::Params\fR
.IX Subsection "Type::Params"
.PP
.Vb 3
\& use Types::Standard qw( Num Object );
\& use Type::Params qw( compile );
\& use Devel::StrictMode qw( STRICT );
\&
\& sub add_number {
\& state $check;
\& $check = compile(Object, Num) if STRICT;
\&
\& my ($self, $num) = STRICT ? $check\->(@_) : @_;
\& push @{ $self\->numbers }, $num;
\& return $self;
\& }
.Ve
.PP
Again, you need to be careful to ensure consistent behaviour if you're
using coercions, defaults, slurpies, etc.
.PP
\fIAd-Hoc Type Checks\fR
.IX Subsection "Ad-Hoc Type Checks"
.PP
.Vb 5
\& ...;
\& my $x = get_some_number();
\& assert_Int($x) if STRICT;
\& return $x + 1;
\& ...;
.Ve
.SH "NEXT STEPS"
.IX Header "NEXT STEPS"
Here's your next step:
.IP "\(bu" 4
Type::Tiny::Manual::Coercions
.Sp
Advanced information on coercions.
.SH "AUTHOR"
.IX Header "AUTHOR"
Toby Inkster <tobyink@cpan.org>.
.SH "COPYRIGHT AND LICENCE"
.IX Header "COPYRIGHT AND LICENCE"
This software is copyright (c) 2013\-2014, 2017\-2021 by Toby Inkster.
.PP
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
.SH "DISCLAIMER OF WARRANTIES"
.IX Header "DISCLAIMER OF WARRANTIES"
\&\s-1THIS PACKAGE IS PROVIDED \*(L"AS IS\*(R" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\s0