473,587 Members | 2,605 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

do/while Vs For: is there a real difference in performance?


A little while ago I opined that do/while loops are harder to
read than for loops, and therefore I preferred using for loops.

However, it was pointed out that do/while has significant
performance benefits as evidenced by:

<URL:http://www.websiteopti mization.com/speed/10/10-2.html>

(There's a bug in the page, testLoop is both a function name
and the name of the form but if you download the page & rename
the function and the call, all is OK)

So having written a poorly performing 'getElementsByC lassName'
(gEBCN) function using for, I re-wrote the function using
do/while reversed which the above link would have me believe
provides a huge benefit in speed.

Using do/while reversed provides about 23% reduction in time
(averaged over 20 or so runs).

It has also been said that testing the length of an array or
collection each iteration is slower than storing it in a variable
and testing against that, i.e.

for (var i=0; i<anArray.lengt h; i++)

is slower than:

for (var i=0, j=anArray.lengt h; i<j; i++)

So I tested that too. Remarkably, that provides almost as big a
saving as do/while loop, 22%.

Finally, I tried a reversed for, but it was slower than a forward
loop probably because it had to evaluate i>=0 rather than i<n.

So it seems to me that for most purposes, users will not tell any
difference between a for loop and the most optimised do/while,
provided the test parameter is a constant and not some evaluated
value (as per the second for example above).

Comments?

Note: uncommenting the alerts makes the scripts report
slower times, even though the alerts are after the timed
script has finished.

--
Rob
<script type="text/javascript">

// Standard for loop
function getElementsByCl assNameA(c) {
var cArray = [];
var n = document.getEle mentsByTagName( 'body')[0];
var z = new RegExp('\\b' + c + '\\b');

function doTree(n) {
if (n.className && z.test(n.classN ame)){
cArray.push(n);
}
// Standard (slowest) loop
// for (var i=0; i<n.childNodes. length; i++) {

// using a constant forward (fastest)
for (var i=0, nLen=n.childNod es.length; i<nLen; i++) {

// using a constant and reversed loop
// for (var i=n.childNodes. length-1; i>=0; --i) {
doTree(n.childN odes[i]);
}
}
doTree(n);
return cArray;
}

// do/while reversed
function getElementsByCl assNameB(c) {
var cArray = [];
var n = document.getEle mentsByTagName( 'body')[0];
var z = new RegExp('\\b' + c + '\\b');

function doTree(n) {
if (n.className && z.test(n.classN ame))
cArray.push(n);
var i = n.childNodes.le ngth;
if (i) {
do {
doTree(n.childN odes[--i]);
} while (i)
}
}
doTree(n);
return cArray;
}

// just counts elements in document
function countElements() {
var c = '0';
var n = document.getEle mentsByTagName( 'body')[0];
function doCount(n) {
for (var i=0; i<n.childNodes. length; i++) {
c++;
}
}
doCount(n);
return c;
}

</script>

<table><tr><t d>
<button onclick="
var s = new Date();
var classArray = getElementsByCl assNameA('rob') ;
var f = new Date();
var t = f-s;
var c = countElements() ;
var u = Math.floor(t/c*1000);
/*
alert('That took ' + t + 'ms\n\n'
+ 'Element count: ' + c
+ '\nPer element: ' + u + ' microsecond');
*/
document.getEle mentById('A').v alue += '\n' + t;
">Standard for</button>
</td>
<td>
<input type="button" value="do/while reversed" onclick="
var s = new Date();
var classArray = getElementsByCl assNameB('rob') ;
var f = new Date();
var t = f-s;
var c = countElements() ;
var u = Math.floor(t/c*1000);
/*
alert('That took ' + t + 'ms\n\n'
+ 'Element count: ' + c
+ '\nPer element: ' + u + ' microsecond');
*/
document.getEle mentById('B').v alue += '\n' + t;
">
</td></tr>
<tr>
<td><textarea rows="20" cols="10" id="A"
value=""></textarea></td>
<td><textarea rows="20" cols="10" id="B"
value=""></textarea></td>
</tr>
</table>




Jul 23 '05 #1
3 9466
I thought I was the only one that actually saw that article. It is a
bookmark in my browser now. I also noticed the form name/function name
error lol.

It seems to me that any single isolated optimization will result in
negligable performance from the user's perspective.

My opinion is that "no single drop of water thinks it is responsible
for the flood" applies to this subject. No ONE loop optimized will make
a noticeable performance difference, but when faced with a larger
program, the milliseconds saved by multiple loops and recurring loops
COULD be perceived.

IMO, it seems that every beginning javascript programmer learns forward
"for" loops, so that is a familiar pattern. If we had learned "do"
loops first, would they be easier to read?

Either way, I use only do loops in all my javascript as per that
article. I even implemented the duff super loop 8.

Jul 23 '05 #2
JRS: In article <BE************ ****@news.optus .net.au>, dated Fri, 4
Mar 2005 05:48:17, seen in news:comp.lang. javascript, RobG
<rg***@iinet.ne t.auau> posted :
A little while ago I opined that do/while loops are harder to
read than for loops, and therefore I preferred using for loops.

However, it was pointed out that do/while has significant
performance benefits
...


I did not see you testing anything matching the first loop below, which
seems to me quite readable after one has seen the construction a couple
of times :
N = 1e6
D1 = new Date()
j = N ; while (j--) {}
D2 = new Date()
for (j=0 ; j<N ; j++) {}
D3 = new Date()
for (j=N-1 ; j>=0 ; j--) {}
D4 = new Date()
x = [D2-D1, D3-D2, D4-D3] // gets 2480,4990,3850

Note - two are backwards, one forwards.

In the two FOR loops, j>=0 seems faster than j<N, as is reasonable.

Most loops will be dominated by the body of the loop; but the simplest
WHILE takes half the time of the obvious FOR ... for me.

Then
j = N ; while (j--) {}
for (j=N ; j-- ; ) {}
have similar high speeds - not surprisingly - and the second looks like
a FOR loop.
Perhaps the important point is that the increment and the test should be
combined.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #3
Lee
Dr John Stockton said:
Perhaps the important point is that the increment and the test should be
combined.


That's my impression. The value remains in the register, rather than
having to deal with symbol tables to load it back in again for the
comparison.

I like the look of:

while (j-->0) {}

even though it's probably not as efficient as it might be.

Jul 23 '05 #4

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

Similar topics

1
2237
by: Marc H. | last post by:
Hello, I recently converted one of my perl scripts to python. What the script does is simply search a lot of big mail files (~40MB) to retrieve specific emails. I simply converted the script line by line to python, keeping the algorithms & functions as they were in perl (no optimization). The purpose was mainly to learn python and see the differences with perl. Now, once the converted script was finished, I was amazed to find that
80
5021
by: | last post by:
Is there a performance difference between this: \\\ Dim i As Integer For i = 0 to myObject.Controls.Count - 1 myObject.Controls(i) = ... Next /// and this:
11
2092
by: MLH | last post by:
Suppose I'm in an open database (northwind.mdb). Is there a shorter form of doing the following after I've dim'd dbsNorthwind as database... Set dbsNorthwind = OpenDatabase("Northwind.mdb") ??? Or, should I always use the above syntax in DAO situations where I just want to move about a recordset in the database updating
147
10069
by: Michael B Allen | last post by:
Should there be any preference between the following logically equivalent statements? while (1) { vs. for ( ;; ) { I suspect the answer is "no" but I'd like to know what the consensus is
8
7368
by: Ken Wilson | last post by:
In spite of the obvious advantage of not encountering a NullReferenceException unexpectedly in your running program is there an offset cost in performance for using String.IsNullOrEmpty() over != ""? If so, would it be of any great significance if a large number of strings were being tested over the run of an application? Ken Wilson Seeking viable employment in Victoria, BC
44
3209
by: Don Kim | last post by:
Ok, so I posted a rant earlier about the lack of marketing for C++/CLI, and it forked over into another rant about which was the faster compiler. Some said C# was just as fast as C++/CLI, whereas others said C++/CLI was more optimized. Anyway, I wrote up some very simple test code, and at least on my computer C++/CLI came out the fastest. Here's the sample code, and just for good measure I wrote one in java, and it was the slowest! ;-)...
33
4657
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most of articles I read from different experts and programmers tell me that their "gut feelings" for using stringBuilder instead of string concatenation is when the number of string concatunation is more then N ( N varies between 3 to max 15 from...
7
1199
by: Stephan Rose | last post by:
I am currently working on an EDA app and heavily working on squeezing the last bits of performance out of it. Going as far as sending batches of geometry to the video card while still processing geometry to get some parallization going. Though at least on my hardware, this does not buy me much. I luv my two 7800 GTs in SLI =) But for users with a lower spec video card, this may actually be of help. I am also going ahead and running two...
34
3521
by: raylopez99 | last post by:
StringBuilder better and faster than string for adding many strings. Look at the below. It's amazing how much faster StringBuilder is than string. The last loop below is telling: for adding 200000 strings of 8 char each, string took over 25 minutes while StringBuilder took 40 milliseconds! Can anybody explain such a radical difference?
0
7927
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8220
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
8352
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
7981
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
8222
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...
1
5723
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5396
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3882
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1194
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.