Mark rows with identical values in a table I have an simple algorithm which marks table rows with identical entries blue.  The problem is that this solution takes a lot of time.

Has anyone an idea how to improve the speed of this?

$(document).ready(function(){
   var tableRows = $("#sortable tbody tr");
   tableRows.each(function(n){
      var id = $(this).attr('id'); 
      var example = $(this).children('#example').children('#content').html(); 

      tableRows.each(function(n){
         if($(this).attr('id') != id)
         {
            if ($(this).children('#example').children('#content').html() == example)
            {
               $(this).css('backgroundColor', 'azure');
            }
         }
      });
   });
});


My table looks like this:

&lt;table align="center" id="sortable"&gt;
   &lt;thead&gt;
      &lt;tr bgcolor="orange"&gt;
         &lt;th&gt;Digitcode&lt;/th&gt;
      &lt;/tr&gt;
   &lt;/thead&gt;

   &lt;tbody&gt;
      &lt;tr id="1"&gt;
         &lt;th id="example" class="data"&gt;&lt;div contenteditable id="content"&gt;test&lt;/div&gt;&lt;/th&gt;
      &lt;/tr&gt;
   &lt;/tbody&gt;
&lt;/table&gt;
Without making algorithmic changes, we can still make some performance improvements:

$(document).ready(function() {
    var $tableRows = $("#sortable tbody tr");
    var $rowsToMark = $();

    $tableRows.each(function(n) {
        var id = this.id;
        var example = $(this).find('.content').html();

        $tableRows.each(function(n) {
            var $this;
            if (this.id != id) {
                $this = $(this);
                if ($this.find('.content').html() == example) {
                    $rowsToMark.add($this);
                }
            }
        });
    });

    $rowsToMark.css('backgroundColor', 'azure');
});




If you really want to start optimizing (I seriously doubt it's worth it, though) you could take a dynamic programming approach and do some caching. For instance:


You really don't need to call .html() on any given row more than once. Start by getting the HTML of each row and store it, then you can compare by iterating over those HTML strings rather, than the DOM elements.
If you have already determined that rows A and B are equal, you only need to compare row C against either A or B.
(other things I haven't yet thought of)




General jQuery performance/optimization information:


https://stackoverflow.com/questions/3230727/jquery-optimization-best-practices
https://stackoverflow.com/questions/6028555/jquery-selector-optimization
And many others