title: Table row sorting & string performance
body: <p>I've got a table with a large number of rows that is not suitable for paging. The rows in this table can be sorted by clicking a column header which triggers a client side sorting algoritm based on <a href="http://www.exforsys.com/tutorials/jquery/jquery-basic-alphabetical-sorting.html" rel="nofollow noreferrer">http://www.exforsys.com/tutorials/jquery/jquery-basic-alphabetical-sorting.html</a> The function dynamically adds an "expando" property to each row, thereby caching the key pre-sort: </p>
  
  <pre><code>row.sortKey = $(row).children('td').eq(column).text().toUpperCase();
  </code></pre>
  
  <p>As you can see, the property values are simply set to the contents of the column that was clicked and they are discarded (nulled) once the sorting has finished. Performance is actually surprisingly good - but columns that contain more text appear to be slower to sort. </p>
  
  <p>As the sorting is only done to make it easier for the user to find the row(s) that they are looking for I figured things could be speeded up by cropping the key values with substr(0,7) or something (eight chars should provide more than enough precision). However, I found that doing a substr() incurred more performance cost than it saved, and if anything it made sorting slower. </p>
  
  <p>Does anyone know any (other) optimisations that can be applied to this method? </p>
  
  <p>Here is a more complete example: </p>
  
  <pre><code>var rows = $table.find('tbody &gt; tr').get();
  $.each(rows, function(index, row) {
      row.sortKey = $(row).children('td').eq(column).text().toUpperCase()
  })
  rows.sort(function(a, b) {
      if (a.sortKey &lt; b.sortKey) return -1
      if (a.sortKey &gt; b.sortKey) return 1
      return 0
  })
  $.each(rows, function(index, row) {
      $table.children('tbody').append(row)
      row.sortKey = null
  })
  </code></pre>
  
  <p>EDIT: Here is the final version of my code, incorporating many of the optimisations provided in the answers below: </p>
  
  <pre><code>$('table.sortable').each(function() {
      var $table = $(this);
      var storage = new Array();
      var rows = $table.find('tbody &gt; tr').get();
      $('th', $table).each(function(column) {
          $(this).click(function() {
              var colIndex = this.cellIndex;
              for(i=0;i&lt;rows.length;i++) {
                  rows[i].sortKey = $(rows[i].childNodes[colIndex]).text().toUpperCase();
              }
              rows.sort(function(a, b) {
                  if (a.sortKey &lt; b.sortKey) return -1;
                  if (a.sortKey &gt; b.sortKey) return 1;
                  return 0;
              });
              for(i=0;i&lt;rows.length;i++) {
                  storage.push(rows[i]);
                  rows[i].sortKey = null;
              }
              $table.children('tbody').append(storage);
          });
      });
  });
  </code></pre>