Re: [xsl] How to improve the performance of my matrix addition function?

Subject: Re: [xsl] How to improve the performance of my matrix addition function?
From: "Martin Honnen martin.honnen@xxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Sun, 12 Jul 2020 21:53:24 -0000
On 12.07.2020 22:47, Dr. Roger L Costello costello@xxxxxxxxx wrote:
Hi Folks,

My application uses lots of matrix operations. I used the SAXON Tool Profile
(-TP) option to generate a web page that shows the performance of each of my
matrix operations. I found that my matrix addition function is taking an
appallingly large amount of time. Below is my matrix addition function. Do you
have suggestions on ways to improve its performance?  /Roger

<!-- A matrix can only be added to another matrix if the two matrices have the same dimensions. To add two matrices, just add the corresponding entries, and place this sum in the corresponding position in the matrix which results. --> <xsl:function name="matrix:addition" as="element(Matrix)"> <xsl:param name="M" as="element(Matrix)" /> <xsl:param name="N" as="element(Matrix)" /> <xsl:param name="name-of-result-matrix" as="xs:string" />

     <Matrix id="{$name-of-result-matrix}">
         <xsl:for-each select="1 to count($M/row)">
             <xsl:variable name="i" select="." as="xs:integer"/>
             <row>
                 <xsl:for-each select="1 to count($M/row[$i]/col)">
                     <xsl:variable name="j" select="." as="xs:integer"/>
                     <col>
                         <xsl:value-of select="$M/row[$i]/col[$j] +
$N/row[$i]/col[$j]"/>
                     </col>
                 </xsl:for-each>
             </row>
         </xsl:for-each>
     </Matrix>
</xsl:function>

You could also try to key the row and col elements by their position e.g.


  <xsl:key name="row-by-index" match="Matrix/row">
      <xsl:variable name="key" as="xs:integer">
          <xsl:number/>
      </xsl:variable>
      <xsl:sequence select="$key"/>
  </xsl:key>

  <xsl:key name="col-by-index" match="Matrix/row/col">
      <xsl:variable name="key" as="xs:integer">
          <xsl:number/>
      </xsl:variable>
      <xsl:sequence select="$key"/>
  </xsl:key>


<Matrix id="{$name-of-result-matrix}"> <xsl:for-each select="$M/row"> <xsl:variable name="row2" select="key('row-by-index', position(), $N)"/> <row> <xsl:for-each select="col"> <col> <xsl:value-of select=". + key('col-by-index', position(), $row2)"/> </col> </xsl:for-each> </row> </xsl:for-each> </Matrix>


The keys could also be used in your original version where you process the (1 to count(...)) sequences.

And of course in XPath 3/XSLT 3 there is the "for-each-pair" function
made for tasks like this but I have no idea whether that would perform
better. And to write it solely as a function expression you need XQuery
or the XPath 4 extension function introduced in Saxon 10 to create elements.

Current Thread