Reputation: 1091
I read that using recursion with Divide and Conquer method is efficient. Could anyone suggest how can i improve the recursion call below. All it does is repeat the element "a", 80 times to the output. However it just repeats eighty times without any algorithm. Also how does it improve the performance(any links or pointers?)
<xsl:variable name="maxcount" select="'80'" />
<xsl:variable name="count" select="'1'" />
<xsl:if test="$count > 0">
<xsl:call-template name="copyrec">
<xsl:with-param name="index" select="'1'" />
</xsl:call-template>
</xsl:if>
<xsl:template name="copyrec">
<xsl:param name="index" />
<xsl:if test="$index <= $maxcount">
<xsl:variable name="tmpind" select="$index"/>
<a>this element repeats 80 times</a>
<xsl:call-template name="copyrec">
<xsl:with-param name="index" select="$tmpind + 1" />
</xsl:call-template>
</xsl:if>
</xsl:template>
Upvotes: 1
Views: 1095
Reputation: 163262
Divide and conquer will reduce the amount of stack space used by this code, but it will not make it any faster. For 80 repetitions, there is almost certainly enough stack space, so you might as well use it. For 10000 repetitions, your code will still run fine if the processor implements tail call optimization. But if you want to be sure not to run out of stack space even with 10000 iterations and with a processor that doesn't do this basic optimization, then D+C is also very simple for this case:
<xsl:template name="copyrec">
<xsl:param name="count" />
<xsl:choose>
<xsl:when test="$count = 0"/> <!-- do nothing -->
<xsl:when test="$count = 1">
<a>this element repeats 80 times</a>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="copyrec">
<xsl:with-param name="count" select="floor($count div 2)" />
</xsl:call-template>
<xsl:call-template name="copyrec">
<xsl:with-param name="count" select="$count - floor($count div 2)" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Upvotes: 2