{
    "content": [
        {
            "type": "text",
            "text": "# Type::Tiny::Manual::Optimization (perldoc)\n\n## NAME\n\nType::Tiny::Manual::Optimization - squeeze the most out of your CPU\n\n## Sections\n\n- **NAME**\n- **MANUAL** (4 subsections)\n- **NEXT STEPS**\n- **AUTHOR**\n- **COPYRIGHT AND LICENCE**\n- **DISCLAIMER OF WARRANTIES**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Type::Tiny::Manual::Optimization",
        "section": "",
        "mode": "perldoc",
        "summary": "Type::Tiny::Manual::Optimization - squeeze the most out of your CPU",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "MANUAL",
                "lines": 58,
                "subsections": [
                    {
                        "name": "Inlining Type Constraints",
                        "lines": 84
                    },
                    {
                        "name": "Inlining Coercions",
                        "lines": 7
                    },
                    {
                        "name": "Common Sense",
                        "lines": 8
                    },
                    {
                        "name": "Devel::StrictMode",
                        "lines": 43
                    }
                ]
            },
            {
                "name": "NEXT STEPS",
                "lines": 6,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "COPYRIGHT AND LICENCE",
                "lines": 5,
                "subsections": []
            },
            {
                "name": "DISCLAIMER OF WARRANTIES",
                "lines": 4,
                "subsections": []
            }
        ],
        "sections": {
            "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 you can use to get the\nbest performance out of it.\n\nXS\nThe simplest thing you can do to increase performance of many of the built-in type constraints\nis to install Type::Tiny::XS, a set of ultra-fast type constraint checks implemented in C.\n\nType::Tiny will attempt to load Type::Tiny::XS and use its type checks. If Type::Tiny::XS is not\navailable, it will then try to use Mouse *if it is already loaded*, but Type::Tiny won't attempt\nto load Mouse for you.\n\nCertain type constraints can also be accelerated if you have Ref::Util::XS installed.\n\nTypes that can be accelerated by Type::Tiny::XS\nThe following simple type constraints from Types::Standard will be accelerated by\nType::Tiny::XS: Any, ArrayRef, Bool, ClassName, CodeRef, Defined, FileHandle, GlobRef, HashRef,\nInt, Item, Object, Map, Ref, ScalarRef, Str, Tuple, Undef, and Value. (Note that Num and\nRegexpRef are *not* on that list.)\n\nThe parameterized form of Ref cannot be accelerated.\n\nThe parameterized forms of ArrayRef, HashRef, and Map can be accelerated only if their\nparameters are.\n\nThe parameterized form of Tuple can be accelerated if its parameters are, it has no Optional\ncomponents, and it does not use \"slurpy\".\n\nCertain type constraints may benefit partially from Type::Tiny::XS. For example, RoleName\ninherits from ClassName, so part of the type check will be conducted by Type::Tiny::XS.\n\nThe parameterized InstanceOf, HasMethods, and Enum type constraints will be accelerated. So will\nType::Tiny::Class, Type::Tiny::Duck, and Type::Tiny::Enum objects.\n\nThe PositiveInt and PositiveOrZeroInt type constraints from Types::Common::Numeric will be\naccelerated, as will the NonEmptyStr type constraint from Types::Common::String.\n\nThe StringLike, CodeLike, HashLike, and ArrayLike types from Types::TypeTiny will be\naccelerated, but parameterized HashLike and ArrayLike will not.\n\nType::Tiny::Union and Type::Tiny::Intersection will also be accelerated if their constituent\ntype constraints are.\n\nTypes that can be accelerated by Mouse\nThe following simple type constraints from Types::Standard will be accelerated by\nType::Tiny::XS: Any, ArrayRef, Bool, ClassName, CodeRef, Defined, FileHandle, GlobRef, HashRef,\nRef, ScalarRef, Str, Undef, and Value. (Note that Item, Num, Int, Object, and RegexpRef are\n*not* on that list.)\n\nThe parameterized form of Ref cannot be accelerated.\n\nThe parameterized forms of ArrayRef and HashRef can be accelerated only if their parameters are.\n\nCertain type constraints may benefit partially from Mouse. For example, RoleName inherits from\nClassName, so part of the type check will be conducted by Mouse.\n\nThe parameterized InstanceOf and HasMethods type constraints will be accelerated. So will\nType::Tiny::Class and Type::Tiny::Duck objects.\n",
                "subsections": [
                    {
                        "name": "Inlining Type Constraints",
                        "content": "In 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 type constraint, and your\ncoderef to check that the value is above zero.\n\nSub calls in Perl are relatively expensive in terms of memory and CPU usage, so it would be good\nif it could be done all in one sub call.\n\nThe Int type constraint knows how to create a string of Perl code that checks an integer. It's\nsomething like the following. (It's actually more complicated, but this is close enough as an\nexample.)\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 constraints as strings is\na really simple and easy way of optimizing type checks.\n\nBut it can be made even more efficient. Type::Tiny needs to localize $ and copy the value into\nit for the above check. If you're checking ArrayRef[$type] this will be done for each element of\nthe array. Things could 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 variable name and can use that\nin 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 and \"&&\" your own string\nwith it, Type::Tiny provides a shortcut for this. Just return a list of strings to smush\ntogether with \"&&\", and if 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 particular case. You'll note that\nwe're checking the string matches \"/^-?[0-9+]$/\" and then checking it's greater than or equal to\nzero. But a non-negative integer won't ever start with a minus sign, so we could inline the\ncheck to something like:\n\n$ =~ /^[0-9]+$/\n\nWhile an inlined check *can* call its parent type check, it is not required 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 your own check is at least\nas rigorous.\n"
                    },
                    {
                        "name": "Inlining Coercions",
                        "content": "Moo is the only object-oriented programming toolkit that fully supports coercions being inlined,\nbut even for Moose and Mouse, providing coercions as strings can help Type::Tiny optimize its\ncoercion features.\n\nFor Moo, if you want your coercion to be inlinable, all the types you're coercing from and to\nneed to be inlinable, plus the coercion needs to be given as a string of Perl code.\n"
                    },
                    {
                        "name": "Common Sense",
                        "content": "The HashRef[ArrayRef] type constraint can probably be checked faster than\nHashRef[ArrayRef[Num]]. If you find yourself using very complex and slow type constraints, you\nshould consider switching to simpler and faster ones. (Though this means you have to place a\nlittle more trust in your caller to not supply you with bad data.)\n\n(A counter-intuitive exception to this: even though Int is more restrictive than Num, in most\ncircumstances Int checks will run faster.)\n"
                    },
                    {
                        "name": "Devel::StrictMode",
                        "content": "One possibility is to use strict type checks when you're running your release tests, and faster,\nmore permissive type checks at other times. Devel::StrictMode can make this easier.\n\nThis provides a \"STRICT\" constant that indicates whether your code is operating in \"strict mode\"\nbased on certain environment variables.\n\nAttributes\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 it can lead to\ninconsistent and unpredictable behaviour.\n\nType::Params\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 using coercions,\ndefaults, slurpies, etc.\n\nAd-Hoc Type Checks\n...;\nmy $x = getsomenumber();\nassertInt($x) if STRICT;\nreturn $x + 1;\n...;\n"
                    }
                ]
            },
            "NEXT STEPS": {
                "content": "Here's your next step:\n\n*   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 the same terms as the Perl\n5 programming language system itself.\n",
                "subsections": []
            },
            "DISCLAIMER OF WARRANTIES": {
                "content": "THIS PACKAGE IS PROVIDED \"AS IS\" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nWITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.\n",
                "subsections": []
            }
        }
    }
}