<cache-return> cache returned values

name
cache-return
xml namespace
http://moyaproject.com

Return a value from a cache, if it exists. Otherwise, execute the enclosed block.

This tag can be used to memoize a <macro> or other callable. Essentially, this means that if you call the macro a second time with the same parameters, it returns the previously calculated result. For macros that are slow to execute, this can result in significant speedups.

For example, the following code calculates the factorial of a number:

<moya xmlns="http://moyaproject.com"
    xmlns:let="http://moyaproject.com/let">

    <macro docname="fact">
        <signature>
            <argument name="n"/>
        </signature>
        <cache-return key="n">
            <echo>calculating ${n}!</echo>
            <let f="1"/>
            <while test="n">
                <let f="f*n" n="n-1"/>
            </while>
            <return value="f"/>
        </cache-return>
    </macro>

    <macro docname="main">
        <call macro="fact" let:n="7" dst="result"/>
        <echo>${result}</echo>
        <call macro="fact" let:n="7" dst="result"/>
        <echo>${result}</echo>
        <call macro="fact" let:n="7" dst="result"/>
        <echo>${result}</echo>
    </macro>

</moya>

If you run the above code, you will get the following output:

$ moya run cachereturn.xml
calculating 7!
5040
5040
5040

The first time the fact macro is called, Moya displays "calculating 7!" in the terminal. The second and third time, the text is not displayed because the result is retrieved from the cache – without the need to execute the code within <cache-return>.

attributes
name purpose type required? default choices
cache Cache name text No "runtime"
for Time to cache for timespan No
key Cache key text No
keydata Cache data expression No None
local Should the value be cached for this tag only? boolean No yes
inherited attributes
name purpose type required? default choices
if Conditional expression expression No yes