patternjavascriptMinor
Mark rows with identical values in a table
Viewed 0 times
rowswithidenticalvaluestablemark
Problem
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?
My table looks like this:
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:
Digitcode
test
Solution
Without making algorithmic changes, we can still make some performance improvements:
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:
General jQuery performance/optimization information:
$(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
Code Snippets
$(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');
});Context
StackExchange Code Review Q#6470, answer score: 6
Revisions (0)
No revisions yet.