{
    "mode": "info",
    "parameter": "Type::Tiny::Manual::Optimization",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/info/Type%3A%3ATiny%3A%3AManual%3A%3AOptimization/json",
    "generated": "2026-07-05T13:51:49Z",
    "sections": {
        "Type::Tiny::Manual::OpUserzContributed PeType::Tiny::Manual::Optimization(3pm)": {
            "content": "",
            "subsections": []
        },
        "NAME": {
            "content": "Type::Tiny::Manual::Optimization - squeeze the most out of your CPU\n",
            "subsections": []
        },
        "MANUAL": {
            "content": "Type::Tiny is written with efficiency in mind, but there are techniques\nyou can use to get the best performance out of it.\n\nXS\nThe simplest thing you can do to increase performance of many of the\nbuilt-in type constraints is to install Type::Tiny::XS, a set of ultra-\nfast type constraint checks implemented in C.\n\nType::Tiny will attempt to load Type::Tiny::XS and use its type checks.\nIf Type::Tiny::XS is not available, it will then try to use Mouse if it\nis already loaded, but Type::Tiny won't attempt to load Mouse for you.\n\nCertain type constraints can also be accelerated if you have\nRef::Util::XS installed.\n\nTypes that can be accelerated by Type::Tiny::XS\n\nThe following simple type constraints from Types::Standard will be\naccelerated by Type::Tiny::XS: Any, ArrayRef, Bool, ClassName, CodeRef,\nDefined, FileHandle, GlobRef, HashRef, Int, Item, Object, Map, Ref,\nScalarRef, Str, Tuple, Undef, and Value. (Note that Num and RegexpRef\nare not on that list.)\n\nThe parameterized form of Ref cannot be accelerated.\n\nThe parameterized forms of ArrayRef, HashRef, and Map can be\naccelerated only if their parameters are.\n\nThe parameterized form of Tuple can be accelerated if its parameters\nare, it has no Optional components, and it does not use \"slurpy\".\n\nCertain type constraints may benefit partially from Type::Tiny::XS.\nFor example, RoleName inherits from ClassName, so part of the type\ncheck will be conducted by Type::Tiny::XS.\n\nThe parameterized InstanceOf, HasMethods, and Enum type constraints\nwill be accelerated. So will Type::Tiny::Class, Type::Tiny::Duck, and\nType::Tiny::Enum objects.\n\nThe PositiveInt and PositiveOrZeroInt type constraints from\nTypes::Common::Numeric will be accelerated, as will the NonEmptyStr\ntype constraint from Types::Common::String.\n\nThe StringLike, CodeLike, HashLike, and ArrayLike types from\nTypes::TypeTiny will be accelerated, but parameterized HashLike and\nArrayLike will not.\n\nType::Tiny::Union and Type::Tiny::Intersection will also be accelerated\nif their constituent type constraints are.\n\nTypes that can be accelerated by Mouse\n\nThe following simple type constraints from Types::Standard will be\naccelerated by Type::Tiny::XS: Any, ArrayRef, Bool, ClassName, CodeRef,\nDefined, FileHandle, GlobRef, HashRef, Ref, ScalarRef, Str, Undef, and\nValue.  (Note that Item, Num, Int, Object, and RegexpRef are not on\nthat list.)\n\nThe parameterized form of Ref cannot be accelerated.\n\nThe parameterized forms of ArrayRef and HashRef can be accelerated only\nif their parameters are.\n\nCertain type constraints may benefit partially from Mouse. For example,\nRoleName inherits from ClassName, so part of the type check will be\nconducted by Mouse.\n\nThe parameterized InstanceOf and HasMethods type constraints will be\naccelerated. So will Type::Tiny::Class and Type::Tiny::Duck objects.\n\nInlining Type Constraints\nIn the case of a type constraint like this:\n\nmy $type = Int->where(sub { $ >= 0 });\n\nType::Tiny will need to call one sub to verify a value meets the Int\ntype constraint, and your coderef to check that the value is above\nzero.\n\nSub calls in Perl are relatively expensive in terms of memory and CPU\nusage, so it would be good if it could be done all in one sub call.\n\nThe Int type constraint knows how to create a string of Perl code that\nchecks an integer. It's something like the following. (It's actually\nmore complicated, but this is close enough as an example.)\n\n$ =~ /^-?[0-9]+$/\n\nIf you provide your check as a string instead of a coderef, like this:\n\nmy $type = Int->where(q{ $ >= 0 });\n\nThen Type::Tiny will be able to combine them into one string:\n\n( $ =~ /^-?[0-9]+$/ ) && ( $ >= 0 )\n\nSo Type::Tiny will be able to check values in one sub call. Providing\nconstraints as strings is a really simple and easy way of optimizing\ntype checks.\n\nBut it can be made even more efficient. Type::Tiny needs to localize $\nand copy the value into it for the above check. If you're checking\nArrayRef[$type] this will be done for each element of the array. Things\ncould be made more efficient if Type::Tiny were able to directly check:\n\n( $arrayref->[$i] =~ /^-?[0-9]+$/ ) && ( $arrayref->[$i] >= 0 )\n\nThis can be done by providing an inlining sub. The sub is given a\nvariable name and can use that in the string of code it generates.\n\nmy $type = Type::Tiny->new(\nparent  => Int,\ninlined => sub {\nmy ($self, $varname) = @;\nreturn sprintf(\n'(%s) && ( %s >= 0 )',\n$self->parent->inlinecheck($varname),\n$varname,\n);\n}\n);\n\nBecause it's pretty common to want to call your parent's inline check\nand \"&&\" your own string with it, Type::Tiny provides a shortcut for\nthis.  Just return a list of strings to smush together with \"&&\", and\nif the first one is \"undef\", Type::Tiny will fill in the blank with the\nparent type check.\n\nmy $type = Type::Tiny->new(\nparent  => Int,\ninlined => sub {\nmy ($self, $varname) = @;\nreturn (\nundef,\nsprintf('%s >= 0', $varname),\n);\n}\n);\n\nThere is one further optimization which can be applied to this\nparticular case. You'll note that we're checking the string matches\n\"/^-?[0-9+]$/\" and then checking it's greater than or equal to zero.\nBut a non-negative integer won't ever start with a minus sign, so we\ncould inline the check to something like:\n\n$ =~ /^[0-9]+$/\n\nWhile an inlined check can call its parent type check, it is not\nrequired to.\n\nmy $type = Type::Tiny->new(\nparent  => Int,\ninlined => sub {\nmy ($self, $varname) = @;\nreturn sprintf('%s =~ /^[0-9]+$/', $varname);\n}\n);\n\nIf you opt not to call the parent type check, then you need to ensure\nyour own check is at least as rigorous.\n\nInlining Coercions\nMoo is the only object-oriented programming toolkit that fully supports\ncoercions being inlined, but even for Moose and Mouse, providing\ncoercions as strings can help Type::Tiny optimize its coercion\nfeatures.\n\nFor Moo, if you want your coercion to be inlinable, all the types\nyou're coercing from and to need to be inlinable, plus the coercion\nneeds to be given as a string of Perl code.\n\nCommon Sense\nThe HashRef[ArrayRef] type constraint can probably be checked faster\nthan HashRef[ArrayRef[Num]]. If you find yourself using very complex\nand slow type constraints, you should consider switching to simpler and\nfaster ones. (Though this means you have to place a little more trust\nin your caller to not supply you with bad data.)\n\n(A counter-intuitive exception to this: even though Int is more\nrestrictive than Num, in most circumstances Int checks will run\nfaster.)\n\nDevel::StrictMode\nOne possibility is to use strict type checks when you're running your\nrelease tests, and faster, more permissive type checks at other times.\nDevel::StrictMode can make this easier.\n\nThis provides a \"STRICT\" constant that indicates whether your code is\noperating in \"strict mode\" based on certain environment variables.\n\nAttributes\n\nuse Types::Standard qw( ArrayRef Num );\nuse Devel::StrictMode qw( STRICT );\n\nhas numbers => (\nis      => 'ro',\nisa     => STRICT ? ArrayRef[Num] : ArrayRef,\ndefault => sub { [] },\n);\n\nIt is inadvisible to do this on attributes that have coercions because\nit can lead to inconsistent and unpredictable behaviour.\n\nType::Params\n\nuse Types::Standard qw( Num Object );\nuse Type::Params qw( compile );\nuse Devel::StrictMode qw( STRICT );\n\nsub addnumber {\nstate $check;\n$check = compile(Object, Num) if STRICT;\n\nmy ($self, $num) = STRICT ? $check->(@) : @;\npush @{ $self->numbers }, $num;\nreturn $self;\n}\n\nAgain, you need to be careful to ensure consistent behaviour if you're\nusing coercions, defaults, slurpies, etc.\n\nAd-Hoc Type Checks\n\n...;\nmy $x = getsomenumber();\nassertInt($x) if STRICT;\nreturn $x + 1;\n...;\n",
            "subsections": []
        },
        "NEXT STEPS": {
            "content": "Here's your next step:\n\no   Type::Tiny::Manual::Coercions\n\nAdvanced information on coercions.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Toby Inkster <tobyink@cpan.org>.\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENCE": {
            "content": "This software is copyright (c) 2013-2014, 2017-2021 by Toby Inkster.\n\nThis is free software; you can redistribute it and/or modify it under\nthe same terms as the Perl 5 programming language system itself.\n",
            "subsections": []
        },
        "DISCLAIMER OF WARRANTIES": {
            "content": "THIS PACKAGE IS PROVIDED \"AS IS\" AND WITHOUT ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF\nMERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n\nperl v5.32.1                      2021-08Type::Tiny::Manual::Optimization(3pm)",
            "subsections": []
        }
    },
    "summary": "Type::Tiny::Manual::Optimization - squeeze the most out of your CPU",
    "flags": [],
    "examples": [],
    "see_also": []
}