Documentation for trait is cached

Documentation for trait is cached, assembled from the following types:

class Routine

From Routine

(Routine) trait is cached

multi sub trait_mod:<is>(Routine $r:$cached!)

NOTE: this feature is currently EXPERIMENTAL.

Causes the return value of a routine to be stored, so that when subsequent calls with the same list of arguments are made, the stored value can be returned immediately instead of re-running the routine.

Useful when storing and returning the computed value is much faster than re-computing it every time, and when the time saving trumps the cost of the use of more memory.

Even if the arguments passed to the routine are "reference types" (such as objects or arrays), then for the purpose of caching they will only be compared based on their contents. Thus the second invocation will hit the cache in this case:

say foo( [123] );   # runs foo 
say foo( [123] );   # doesn't run foo, uses cached value 
use experimental :cached;
 
sub nth-prime(Int:D $x where * > 0is cached {
    say "Calculating {$x}th prime";
    return (2..*).grep(*.is-prime)[$x - 1];
}
 
say nth-prime(43);
say nth-prime(43);
say nth-prime(43);

produces this output:

Calculating 43th prime
191
191
191