473,802 Members | 2,026 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.getEle mentById(id);

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

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

// If this column was the last one sorted, reverse its sort
direction.
if (col == tblEl.lastColum n)
tblEl.reverseSo rt[col] = !tblEl.reverseS ort[col];

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

// Set the table display style to "none" - necessary for Netscape 6
// browsers.
var oldDsply = tblEl.style.dis play;
tblEl.style.dis play = "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.leng th - 1; i++) {

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

// Search the rows that follow the current one for a smaller value.
for (j = i + 1; j < tblEl.rows.leng th; j++) {
testVal = getTextValue(tb lEl.rows[j].cells[col]);
cmp = compareValues(m inVal, testVal);
// Negate the comparison result if the reverse sort flag is set.
if (tblEl.reverseS ort[col])
cmp = -cmp;
// Sort by the second column (team name) if those values are
equal.
if (cmp == 0 && col != 1)
cmp = compareValues(g etTextValue(tbl El.rows[minIdx].cells[1]),
getTextValue(tb lEl.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.removeChi ld(tblEl.rows[minIdx]);
tblEl.insertBef ore(tmpEl, tblEl.rows[i]);
}
}

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

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

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

return false;
}

function makePretty(tblE l, col) {

var i, j;
var rowEl, cellEl;

// Set style classes on each row to alternate their appearance.
for (i = 0; i < tblEl.rows.leng th; i++) {
rowEl = tblEl.rows[i];
rowEl.className = rowEl.className .replace(rowTes t, "");
if (i % 2 != 0)
rowEl.className += " " + rowClsNm;
rowEl.className = normalizeString (rowEl.classNam e);
// 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.classNam e = cellEl.classNam e.replace(colTe st, "");
if (j == col)
cellEl.classNam e += " " + colClsNm;
cellEl.classNam e = normalizeString (cellEl.classNa me);
}
}

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

Jan 3 '06 #1
5 2400
lo*****@gmail.c om 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.getEle mentById(id);

// The first time this function is called for a given table, set up
// an array of reverse sort flags.
if (tblEl.reverseS ort == null) {
tblEl.reverseSo rt = new Array();
// Also, assume the team name column is initially sorted.
tblEl.lastColum n = 1;
}
It is error-prone to add new properties to host objects like
HTMLTableElemen t 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.or g/wiki/Sorting_algorit hm>

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
HTMLTableRowEle ment objects in the comparator or rebuild the table
afterwards according to the array.
[...]
for (i = 0; i < tblEl.rows.leng th - 1; i++) {
Replace with

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

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

But you should instead use the `tbody' element to distinguish between table
rows in the table header and the table body. HTMLTableSectio nElement
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.removeChi ld(tblEl.rows[minIdx]);
tblEl.insertBef ore(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::insertBef ore
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(tblE l, 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.classNam e);
// 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.len gth; i++) {
See above.
[...]


And probably I forgot to mention something.
HTH

PointedEars
Jan 3 '06 #2
lo*****@gmail.c om 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.getEle mentById(id);

// The first time this function is called for a given table, set up
// an array of reverse sort flags.
if (tblEl.reverseS ort == null) {
tblEl.reverseSo rt = new Array();
// Also, assume the team name column is initially sorted.
tblEl.lastColum n = 1;
}
It is error-prone to add new properties to host objects like
HTMLTableElemen t 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.or g/wiki/Sorting_algorit hm>

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
HTMLTableRowEle ment objects in the comparator or rebuild the table
afterwards according to the array.
[...]
for (i = 0; i < tblEl.rows.leng th - 1; i++) {
Replace with

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

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

But you should instead use the `tbody' element to distinguish between table
rows in the table header and the table body. HTMLTableSectio nElement
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.removeChi ld(tblEl.rows[minIdx]);
tblEl.insertBef ore(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::insertBef ore
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(tblE l, 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.classNam e);
// 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.len gth; i++) {
See above.
[...]


And probably I forgot to mention something.
HTH

PointedEars
Jan 3 '06 #3

lo*****@gmail.c om 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*********@we b.de> wrote:
It is error-prone to add new properties to host objects like
HTMLTableElemen t 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.leng th; j++) {


Replace with

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

/\
that won't work, (should be len2) / \
if (minIdx > i) {
tmpEl = tblEl.removeChi ld(tblEl.rows[minIdx]);
tblEl.insertBef ore(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::insertBef ore
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(tblE l, 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.co m escreveu:
lo*****@gmail.c om 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
23076
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
2484
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, callable(*args)) return proxy which, is functionally equivalent to
28
2610
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 almost any operating system? Or is there many other reasons why? I understand there is ansi/iso C and C++ and that ANSI/ISO Code will work on any system If this is the reason why, than why don't developers create specific Python Distrubutions...
7
3050
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 studio 2003 .net optimization were enhanced and that i must gain in performance if I switch to VS 2003 or intel compiler. So I send him the project and he returned a compiled DLL with VS 2003. Result : the VS 2003 compiled Dll is slower than the VC6...
11
2007
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
6257
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
6505
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 using a code loop and an INSERT INTO query. About 800,000 records of raw text. Later, I can then loop through and parse these 800,000 strings into usable data using more code. The problem I have is that the conversion of the text file, using a...
11
2253
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 Can you check if I'm using the clock() function correctly? the function is finding the number in the array that is closest to a number given by the user. Here is the code for the pass by value function. Thanks for the help! relevant code:
47
1441
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 it can be ten times slower. Is that correct? I'm quite competent at writing code myself and so most of my code will be quite well written, and I don't want to move to vb.net if well written VB6 code is ten times faster. Have I been told the...
0
9562
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10538
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10305
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10285
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10063
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5494
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3792
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2966
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.