1Type::Tiny::Manual::OptUismeirzaCtoinotnr(i3b)uted PerlTDyopceu:m:eTnitnayt:i:oMnanual::Optimization(3)
2
3
4

NAME

6       Type::Tiny::Manual::Optimization - squeeze the most out of your CPU
7

MANUAL

9       Type::Tiny is written with efficiency in mind, but there are techniques
10       you can use to get the best performance out of it.
11
12   XS
13       The simplest thing you can do to increase performance of many of the
14       built-in type constraints is to install Type::Tiny::XS, a set of ultra-
15       fast type constraint checks implemented in C.
16
17       Type::Tiny will attempt to load Type::Tiny::XS and use its type checks.
18       If Type::Tiny::XS is not available, it will then try to use Mouse if it
19       is already loaded, but Type::Tiny won't attempt to load Mouse for you.
20
21       Certain type constraints can also be accelerated if you have
22       Ref::Util::XS installed.
23
24       Types that can be accelerated by Type::Tiny::XS
25
26       The following simple type constraints from Types::Standard will be
27       accelerated by Type::Tiny::XS: "Any", "ArrayRef", "Bool", "ClassName",
28       "CodeRef", "Defined", "FileHandle", "GlobRef", "HashRef", "Int",
29       "Item", "Object", "Map", "Ref", "ScalarRef", "Str", "Tuple", "Undef",
30       and "Value". (Note that "Num" and "RegexpRef" are not on that list.)
31
32       The parameterized form of "Ref" cannot be accelerated.
33
34       The parameterized forms of "ArrayRef", "HashRef", and "Map" can be
35       accelerated only if their parameters are.
36
37       The parameterized form of "Tuple" can be accelerated if its parameters
38       are, it has no "Optional" components, and it does not use "slurpy".
39
40       Certain type constraints may benefit partially from Type::Tiny::XS.
41       For example, "RoleName" inherits from "ClassName", so part of the type
42       check will be conducted by Type::Tiny::XS.
43
44       The parameterized "InstanceOf", "HasMethods", and "Enum" type
45       constraints will be accelerated. So will Type::Tiny::Class,
46       Type::Tiny::Duck, and Type::Tiny::Enum objects. (But enums will only be
47       accelerated if the list of allowed string values consist entirely of
48       word characters and hyphens - that is: "not grep /[^\w-]/, @values".)
49
50       The "PositiveInt" and "PositiveOrZeroInt" type constraints from
51       Types::Common::Numeric will be accelerated, as will the "NonEmptyStr"
52       type constraint from Types::Common::String.
53
54       Type::Tiny::Union and Type::Tiny::Intersection will also be accelerated
55       if their constituent type constraints are.
56
57       Types that can be accelerated by Mouse
58
59       The following simple type constraints from Types::Standard will be
60       accelerated by Type::Tiny::XS: "Any", "ArrayRef", "Bool", "ClassName",
61       "CodeRef", "Defined", "FileHandle", "GlobRef", "HashRef", "Ref",
62       "ScalarRef", "Str", "Undef", and "Value".  (Note that "Item", "Num",
63       "Int", "Object", and "RegexpRef" are not on that list.)
64
65       The parameterized form of "Ref" cannot be accelerated.
66
67       The parameterized forms of "ArrayRef" and "HashRef" can be accelerated
68       only if their parameters are.
69
70       Certain type constraints may benefit partially from Mouse. For example,
71       "RoleName" inherits from "ClassName", so part of the type check will be
72       conducted by Mouse.
73
74       The parameterized "InstanceOf" and "HasMethods" type constraints will
75       be accelerated. So will Type::Tiny::Class and Type::Tiny::Duck objects.
76
77   Inlining Type Constraints
78       In the case of a type constraint like this:
79
80        my $type = Int->where(sub { $_ >= 0 });
81
82       Type::Tiny will need to call one sub to verify a value meets the Int
83       type constraint, and your coderef to check that the value is above
84       zero.
85
86       Sub calls in Perl are relatively expensive in terms of memory and CPU
87       usage, so it would be good if it could be done all in one sub call.
88
89       The Int type constraint knows how to create a string of Perl code that
90       checks an integer. It's something like the following. (It's actually
91       more complicated, but this is close enough as an example.)
92
93        $_ =~ /^-?[0-9]+$/
94
95       If you provide your check as a string instead of a coderef, like this:
96
97        my $type = Int->where(q{ $_ >= 0 });
98
99       Then Type::Tiny will be able to combine them into one string:
100
101        ( $_ =~ /^-?[0-9]+$/ ) && ( $_ >= 0 )
102
103       So Type::Tiny will be able to check values in one sub call. Providing
104       constraints as strings is a really simple and easy way of optimizing
105       type checks.
106
107       But it can be made even more efficient. Type::Tiny needs to localize $_
108       and copy the value into it for the above check. If you're checking
109       ArrayRef[$type] this will be done for each element of the array. Things
110       could be made more efficient if Type::Tiny were able to directly check:
111
112        ( $arrayref->[$i] =~ /^-?[0-9]+$/ ) && ( $arrayref->[$i] >= 0 )
113
114       This can be done by providing an inlining sub. The sub is given a
115       variable name and can use that in the string of code it generates.
116
117        my $type = Type::Tiny->new(
118          parent  => Int,
119          inlined => sub {
120            my ($self, $varname) = @_;
121            return sprintf(
122              '(%s) && ( %s >= 0 )',
123              $self->parent->inline_check($varname),
124              $varname,
125            );
126          }
127        );
128
129       Because it's pretty common to want to call your parent's inline check
130       and "&&" your own string with it, Type::Tiny provides a shortcut for
131       this.  Just return a list of strings to smush together with "&&", and
132       if the first one is "undef", Type::Tiny will fill in the blank with the
133       parent type check.
134
135        my $type = Type::Tiny->new(
136          parent  => Int,
137          inlined => sub {
138            my ($self, $varname) = @_;
139            return (
140              undef,
141              sprintf('%s >= 0', $varname),
142            );
143          }
144        );
145
146       There is one further optimization which can be applied to this
147       particular case. You'll note that we're checking the string matches
148       "/^-?[0-9+]$/" and then checking it's greater than or equal to zero.
149       But a non-negative integer won't ever start with a minus sign, so we
150       could inline the check to something like:
151
152        $_ =~ /^[0-9]+$/
153
154       While an inlined check can call its parent type check, it is not
155       required to.
156
157        my $type = Type::Tiny->new(
158          parent  => Int,
159          inlined => sub {
160            my ($self, $varname) = @_;
161            return sprintf('%s =~ /^[0-9]+$/', $varname);
162          }
163        );
164
165       If you opt not to call the parent type check, then you need to ensure
166       your own check is at least as rigorous.
167
168   Inlining Coercions
169       Moo is the only object-oriented programming toolkit that fully supports
170       coercions being inlined, but even for Moose and Mouse, providing
171       coercions as strings can help Type::Tiny optimize its coercion
172       features.
173
174       For Moo, if you want your coercion to be inlinable, all the types
175       you're coercing from and to need to be inlinable, plus the coercion
176       needs to be given as a string of Perl code.
177
178   Common Sense
179       The "HashRef[ArrayRef]" type constraint can probably be checked faster
180       than "HashRef[ArrayRef[Num]]". If you find yourself using very complex
181       and slow type constraints, you should consider switching to simpler and
182       faster ones. (Though this means you have to place a little more trust
183       in your caller to not supply you with bad data.)
184
185       (A counter-intuitive exception to this: even though "Int" is more
186       restrictive than "Num", in most circumstances "Int" checks will run
187       faster.)
188
189   Devel::StrictMode
190       One possibility is to use strict type checks when you're running your
191       release tests, and faster, more permissive type checks at other times.
192       Devel::StrictMode can make this easier.
193
194       This provides a "STRICT" constant that indicates whether your code is
195       operating in "strict mode" based on certain environment variables.
196
197       Attributes
198
199        use Types::Standard qw( ArrayRef Num );
200        use Devel::StrictMode qw( STRICT );
201
202        has numbers => (
203          is      => 'ro',
204          isa     => STRICT ? ArrayRef[Num] : ArrayRef,
205          default => sub { [] },
206        );
207
208       It is inadvisible to do this on attributes that have coercions because
209       it can lead to inconsistent and unpredictable behaviour.
210
211       Type::Params
212
213        use Types::Standard qw( Num Object );
214        use Type::Params qw( compile );
215        use Devel::StrictMode qw( STRICT );
216
217        sub add_number {
218          state $check;
219          $check = compile(Object, Num) if STRICT;
220
221          my ($self, $num) = STRICT ? $check->(@_) : @_;
222          push @{ $self->numbers }, $num;
223          return $self;
224        }
225
226       Again, you need to be careful to ensure consistent behaviour if you're
227       using coercions, defaults, slurpies, etc.
228
229       Ad-Hoc Type Checks
230
231        ...;
232        my $x = get_some_number();
233        assert_Int($x) if STRICT;
234        return $x + 1;
235        ...;
236

NEXT STEPS

238       Here's your next step:
239
240       ยท   Type::Tiny::Manual::Coercions
241
242           Advanced information on coercions.
243

AUTHOR

245       Toby Inkster <tobyink@cpan.org>.
246
248       This software is copyright (c) 2013-2014, 2017-2020 by Toby Inkster.
249
250       This is free software; you can redistribute it and/or modify it under
251       the same terms as the Perl 5 programming language system itself.
252

DISCLAIMER OF WARRANTIES

254       THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
255       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
256       MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
257
258
259
260perl v5.30.1                      2020-02-12Type::Tiny::Manual::Optimization(3)
Impressum