473,404 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

is there a way to speed up this tablesort code?

I got this tablesort code from
http://www.brainjar.com/dhtml/tablesort/default7.asp

This is very slow for my table of 10 columns and 400 rows. Is there a
way to optimize this code make it screaming fast?

function sortTable(id, col, rev) {

// Get the table or table section to sort.
var tblEl = document.getElementById(id);

// The first time this function is called for a given table, set up
an
// array of reverse sort flags.
if (tblEl.reverseSort == null) {
tblEl.reverseSort = new Array();
// Also, assume the team name column is initially sorted.
tblEl.lastColumn = 1;
}

// If this column has not been sorted before, set the initial sort
direction.
if (tblEl.reverseSort[col] == null)
tblEl.reverseSort[col] = rev;

// If this column was the last one sorted, reverse its sort
direction.
if (col == tblEl.lastColumn)
tblEl.reverseSort[col] = !tblEl.reverseSort[col];

// Remember this column as the last one sorted.
tblEl.lastColumn = col;

// Set the table display style to "none" - necessary for Netscape 6
// browsers.
var oldDsply = tblEl.style.display;
tblEl.style.display = "none";

// Sort the rows based on the content of the specified column using a
// selection sort.

var tmpEl;
var i, j;
var minVal, minIdx;
var testVal;
var cmp;

for (i = 0; i < tblEl.rows.length - 1; i++) {

// Assume the current row has the minimum value.
minIdx = i;
minVal = getTextValue(tblEl.rows[i].cells[col]);

// Search the rows that follow the current one for a smaller value.
for (j = i + 1; j < tblEl.rows.length; j++) {
testVal = getTextValue(tblEl.rows[j].cells[col]);
cmp = compareValues(minVal, testVal);
// Negate the comparison result if the reverse sort flag is set.
if (tblEl.reverseSort[col])
cmp = -cmp;
// Sort by the second column (team name) if those values are
equal.
if (cmp == 0 && col != 1)
cmp = compareValues(getTextValue(tblEl.rows[minIdx].cells[1]),
getTextValue(tblEl.rows[j].cells[1]));
// If this row has a smaller value than the current minimum,
remember its
// position and update the current minimum value.
if (cmp > 0) {
minIdx = j;
minVal = testVal;
}
}

// By now, we have the row with the smallest value. Remove it from
the
// table and insert it before the current row.
if (minIdx > i) {
tmpEl = tblEl.removeChild(tblEl.rows[minIdx]);
tblEl.insertBefore(tmpEl, tblEl.rows[i]);
}
}

// Make it look pretty.
makePretty(tblEl, col);

// Set team rankings.
//setRanks(tblEl, col, rev);

// Restore the table's display style.
tblEl.style.display = oldDsply;

return false;
}

function makePretty(tblEl, col) {

var i, j;
var rowEl, cellEl;

// Set style classes on each row to alternate their appearance.
for (i = 0; i < tblEl.rows.length; i++) {
rowEl = tblEl.rows[i];
rowEl.className = rowEl.className.replace(rowTest, "");
if (i % 2 != 0)
rowEl.className += " " + rowClsNm;
rowEl.className = normalizeString(rowEl.className);
// Set style classes on each column (other than the name column) to
// highlight the one that was sorted.
for (j = 1; j < tblEl.rows[i].cells.length; j++) {
cellEl = rowEl.cells[j];
cellEl.className = cellEl.className.replace(colTest, "");
if (j == col)
cellEl.className += " " + colClsNm;
cellEl.className = normalizeString(cellEl.className);
}
}

// Find the table header and highlight the column that was sorted.
var el = tblEl.parentNode.tHead;
rowEl = el.rows[el.rows.length - 1];
// Set style classes for each column as above.
for (i = 1; i < rowEl.cells.length; i++) {
cellEl = rowEl.cells[i];
cellEl.className = cellEl.className.replace(colTest, "");
// Highlight the header of the sorted column.
if (i == col)
cellEl.className += " " + colClsNm;
cellEl.className = normalizeString(cellEl.className);
}
}

Jan 3 '06 #1
5 2386
lo*****@gmail.com wrote:
I got this tablesort code from
http://www.brainjar.com/dhtml/tablesort/default7.asp

This is very slow for my table of 10 columns and 400 rows. Is there a
way to optimize this code make it screaming fast?

function sortTable(id, col, rev) {
// Get the table or table section to sort.
var tblEl = document.getElementById(id);

// The first time this function is called for a given table, set up
// an array of reverse sort flags.
if (tblEl.reverseSort == null) {
tblEl.reverseSort = new Array();
// Also, assume the team name column is initially sorted.
tblEl.lastColumn = 1;
}
It is error-prone to add new properties to host objects like
HTMLTableElement objects.
// Sort the rows based on the content of the specified column using a
// selection sort.
Selection sort is probably the most intuitive sort algorithmbut not a very
efficient one; it has a time complexity of O(n^2) in the best case, average
case and worst case. Try something faster like Quicksort; it has a time
complexity of O(n*log(n)) in the best case and the average case, and O(n^2)
only in the worst case.

<URL:http://en.wikipedia.org/wiki/Sorting_algorithm>

Maybe it is even faster to store the rows into an array, sort that
array by criteria using Array.prototype.sort(), and reorder the actual
HTMLTableRowElement objects in the comparator or rebuild the table
afterwards according to the array.
[...]
for (i = 0; i < tblEl.rows.length - 1; i++) {
Replace with

for (var i = 0, len = tblEl.rows.length - 1; i < len; i--)
{ [...]
for (j = i + 1; j < tblEl.rows.length; j++) {
Replace with

for (var j = i + 1, len2 = tblEl.rows.length; j < len; j++)
{

But you should instead use the `tbody' element to distinguish between table
rows in the table header and the table body. HTMLTableSectionElement
objects have a `rows' property, too.

<URL:http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-67417573>
// By now, we have the row with the smallest value. Remove it from
the
// table and insert it before the current row.
if (minIdx > i) {
tmpEl = tblEl.removeChild(tblEl.rows[minIdx]);
tblEl.insertBefore(tmpEl, tblEl.rows[i]);
}
}
You do not need to remove the element from the DOM tree yourself before
you insert it again. If the first parameter of Node::insertBefore
refers to a node that is already in the DOM tree, it is first removed:

<URL:http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-952280727>
[...]
function makePretty(tblEl, col) {
[...]
if (i % 2 != 0)
Use (i & 1) to test for an odd number i instead, it is probably faster.
rowEl.className += " " + rowClsNm;
rowEl.className = normalizeString(rowEl.className);
// Set style classes on each column (other than the name column) to
// highlight the one that was sorted.
for (j = 1; j < tblEl.rows[i].cells.length; j++) {
See above.
[...]
// Set style classes for each column as above.
for (i = 1; i < rowEl.cells.length; i++) {
See above.
[...]


And probably I forgot to mention something.
HTH

PointedEars
Jan 3 '06 #2
lo*****@gmail.com wrote:
I got this tablesort code from
http://www.brainjar.com/dhtml/tablesort/default7.asp

This is very slow for my table of 10 columns and 400 rows. Is there a
way to optimize this code make it screaming fast?

function sortTable(id, col, rev) {
// Get the table or table section to sort.
var tblEl = document.getElementById(id);

// The first time this function is called for a given table, set up
// an array of reverse sort flags.
if (tblEl.reverseSort == null) {
tblEl.reverseSort = new Array();
// Also, assume the team name column is initially sorted.
tblEl.lastColumn = 1;
}
It is error-prone to add new properties to host objects like
HTMLTableElement objects.
// Sort the rows based on the content of the specified column using a
// selection sort.
Selection sort is probably the most intuitive sorting algorithm, but not a
very efficient one; it has a time complexity of O(n^2) in the best case,
average case and worst case. Try something faster like Quicksort; it has a
time complexity of O(n*log(n)) in the best case and the average case, and
O(n^2) only in the worst case.

<URL:http://en.wikipedia.org/wiki/Sorting_algorithm>

Maybe it is even faster to store the rows into an array, sort that
array by criteria using Array.prototype.sort(), and reorder the actual
HTMLTableRowElement objects in the comparator or rebuild the table
afterwards according to the array.
[...]
for (i = 0; i < tblEl.rows.length - 1; i++) {
Replace with

for (var i = 0, len = tblEl.rows.length - 1; i < len; i--)
{ [...]
for (j = i + 1; j < tblEl.rows.length; j++) {
Replace with

for (var j = i + 1, len2 = tblEl.rows.length; j < len; j++)
{

But you should instead use the `tbody' element to distinguish between table
rows in the table header and the table body. HTMLTableSectionElement
objects have a `rows' property, too.

<URL:http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-67417573>
// By now, we have the row with the smallest value. Remove it from
the
// table and insert it before the current row.
if (minIdx > i) {
tmpEl = tblEl.removeChild(tblEl.rows[minIdx]);
tblEl.insertBefore(tmpEl, tblEl.rows[i]);
}
}
You do not need to remove the element from the DOM tree yourself before
you insert it again. If the first parameter of Node::insertBefore
refers to a node that is already in the DOM tree, it is first removed:

<URL:http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-952280727>
[...]
function makePretty(tblEl, col) {
[...]
if (i % 2 != 0)
Use (i & 1) to test for an odd number i instead, it is probably faster.
rowEl.className += " " + rowClsNm;
rowEl.className = normalizeString(rowEl.className);
// Set style classes on each column (other than the name column) to
// highlight the one that was sorted.
for (j = 1; j < tblEl.rows[i].cells.length; j++) {
See above.
[...]
// Set style classes for each column as above.
for (i = 1; i < rowEl.cells.length; i++) {
See above.
[...]


And probably I forgot to mention something.
HTH

PointedEars
Jan 3 '06 #3

lo*****@gmail.com napisal(a):
I got this tablesort code from
http://www.brainjar.com/dhtml/tablesort/default7.asp

This is very slow for my table of 10 columns and 400 rows. Is there a
way to optimize this code make it screaming fast?


Move it to server side, do the sorting in the database app, send out
ready HTML.
Seriously, you can speed up the sorting algorithm as much as you want,
but juggling 400 elements using DOM functions WILL be slow no matter
what.
I bet using CSS, relative positioning and just changing Y-positions of
existing table rows would be much faster, but I'm scared of my own idea.

Jan 4 '06 #4
On 2006-01-03, Thomas 'PointedEars' Lahn <Po*********@web.de> wrote:
It is error-prone to add new properties to host objects like
HTMLTableElement objects.
// Sort the rows based on the content of the specified column using a
// selection sort.
Selection sort is probably the most intuitive sorting algorithm,


yeah!.
Maybe it is even faster to store the rows into an array, sort that
array by criteria using Array.prototype.sort()
aren't they already an array?
for (j = i + 1; j < tblEl.rows.length; j++) {


Replace with

for (var j = i + 1, len2 = tblEl.rows.length; j < len; j++)
{

/\
that won't work, (should be len2) / \
if (minIdx > i) {
tmpEl = tblEl.removeChild(tblEl.rows[minIdx]);
tblEl.insertBefore(tmpEl, tblEl.rows[i]);
}
}


You do not need to remove the element from the DOM tree yourself before
you insert it again. If the first parameter of Node::insertBefore
refers to a node that is already in the DOM tree, it is first removed:


infact why not use appendchild ? and do without the temporary element
<URL:http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-952280727>
[...]
function makePretty(tblEl, col) {
[...]
if (i % 2 != 0)


Use (i & 1) to test for an odd number i instead, it is probably faster.


probably not noticably faster.

Bye.
Jasen
Jan 4 '06 #5
bw****@gmail.com escreveu:
lo*****@gmail.com napisal(a):
This is very slow for my table of 10 columns and 400 rows. Is there a
way to optimize this code make it screaming fast?


Move it to server side, do the sorting in the database app, send out
ready HTML.


For paged data, sorting by JS will have a really strange result... But
if you don't have a huge amount of records, I think you should use it,
it's better than waiting for a server answer :)

Give a try to my friend's code, it's working reasonably fast...

You can see the code [http://jsfromhell.com/js/TableSort.js] working in
the lists [http://jsfromhell.com/dhtml], the useful part for you is the
"sortCol" function =]

This is just the sorting initialization:
[http://jsfromhell.com/js/sortCode.js]
--
Jonas Raoni Soares Silva
http://www.jsfromhell.com

Jan 4 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: Yang Li Ke | last post by:
Hi guys, Is it possible to know the internet speed of the visitors with php? Thanx -- Yang
34
by: Jacek Generowicz | last post by:
I have a program in which I make very good use of a memoizer: def memoize(callable): cache = {} def proxy(*args): try: return cache except KeyError: return cache.setdefault(args,...
28
by: Maboroshi | last post by:
Hi I am fairly new to programming but not as such that I am a total beginner From what I understand C and C++ are faster languages than Python. Is this because of Pythons ability to operate on...
7
by: YAZ | last post by:
Hello, I have a dll which do some number crunching. Performances (execution speed) are very important in my application. I use VC6 to compile the DLL. A friend of mine told me that in Visual...
11
by: Jim Lewis | last post by:
Has anyone found a good link on exactly how to speed up code using pyrex? I found various info but the focus is usually not on code speedup.
6
by: Jassim Rahma | last post by:
I want to detect the internet speed using C# to show the user on what speed he's connecting to internet?
8
by: SaltyBoat | last post by:
Needing to import and parse data from a large PDF file into an Access 2002 table: I start by converted the PDF file to a html file. Then I read this html text file, line by line, into a table...
11
by: blackx | last post by:
I'm using clock() to measure the speed of my code (testing the speed of passing by value vs passing by reference in function calls). The problem is, the speed returned by my code is always 0.0000000...
47
by: Mike Williams | last post by:
I'm trying to decide whether or not I need to move to a different development tool and I'm told that VB6 code, when well written, can be ten times faster than vb.net, but that if its badly written...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.