473,569 Members | 2,782 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Performance on "for" loops

Hi again...

I'm wondering what could be better in terms of performance between:

var my_array = new Array();
// populate array

for (index in my_array)
{
// do something with my_array[index]
}

....and...

var my_array = new Array();
// populate array
var my_array_length = my_array.length

for (i = 0; index < my_array_length ; index++)
{
// do something with my_array[index]
}

Thanks for your experience!
Feb 6 '06 #1
5 1856
Fabian Vilers said the following on 2/6/2006 7:48 AM:
Hi again...

I'm wondering what could be better in terms of performance between:
The difference in those two loops will depend almost directly on the
array indexes used.
var my_array = new Array();
// populate array

for (index in my_array)
{
// do something with my_array[index]
}
The above loop would pick up something like this:

my_array['someName'] = "something" ;

Whereas the below one won't.
....and...

var my_array = new Array();
// populate array
var my_array_length = my_array.length

for (i = 0; index < my_array_length ; index++)
{
// do something with my_array[index]
}
That one will fail if the array is what is called "sparse" where every
element is not defined:

my_array[1] = "something" ;
my_array[4] = "no 2 or 3";
Thanks for your experience!


Nothing like a good test for you to gain experience:

var my_array = new Array();
// populate array
var begin1 = new Date();
for (index in my_array)
{
// do something with my_array[index]
}
var end1 = new Date();
document.write( 'for-in took ' + end1-begin1 + ' ms to finish.<br>';
var my_array_length = my_array.length

var begin2 = new Date();
for (i = 0; index < my_array_length ; index++)
{
// do something with my_array[index]
}
var end2 = new Date();
document.write( 'for-loop took ' + end2-begin2 + ' ms to finish.<br>';

A third one you might test is a while loop:

var my_array_length = my_array.length
var begin3 = new Date();
while (my_array_lengt h--)
{
// do something with my_array[index]
}
var end3 = new Date();
document.write( 'while loop took ' + end3-begin3 + ' ms to finish.<br>';

And then the test will show you which is faster. Make sure your "do
something with my_array[index]" code is the same in each loop though.
--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Feb 6 '06 #2
VK

Randy Webb wrote:
That one will fail if the array is what is called "sparse" where every
element is not defined:


"where *not* every element is defined", that was your mental intention
to say.

I thought we had an agreement you don't use "array" in your schema, and
I don't show the flows in your schema. Are we going to break the deal?

Feb 6 '06 #3
VK said the following on 2/6/2006 10:56 AM:
Randy Webb wrote:
That one will fail if the array is what is called "sparse" where every
element is not defined:
"where *not* every element is defined", that was your mental intention
to say.


Yes indeed.
I thought we had an agreement you don't use "array" in your schema
<quote
cite="http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/46263f60dbb73f0/15c871342785bcf a?tvc=1&q=Hikks notathome+jagge d#15c871342785b cfa">
I can answer *any* question not directly related to mutil-dimensional
arrays without using any one of those three phrases, and in fact I
wouldn't even consider using any of those terms unless it was directly
related to the question.
</quote>

And then I clarified it even further:

<quote
cite="http://groups.google.c om/group/comp.lang.javas cript/browse_thread/thread/46263f60dbb73f0/b6f00f0a572647b 4?q=Hikksnotath ome+jagged&rnum =1#b6f00f0a5726 47b4">
I said I could discuss arrays, and explain them, without referring to
"jagged", "multi-dimensional" and a "hash array".
</quote>
and I don't show the flows in your schema.
If there is a flaw in what I said in this thread about arrays, then
please point it out. You showed one where I said something in a way that
was obscure and could have been worded better. That is always to the
best of anybody reading the thread. If there is anything else wrong,
then feel free to correct it.
Are we going to break the deal?


I have not broken it :) I have not used those three terms/phrases unless
they were *directly related* to the topic at hand.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Feb 6 '06 #4
Randy Webb wrote:
Fabian Vilers said the following on 2/6/2006 7:48 AM:
var my_array = new Array();
// populate array
var my_array_length = my_array.length

for (i = 0; index < my_array_length ; index++)
{
// do something with my_array[index]
}


That one will fail if the array is what is called "sparse" where every
element is not defined:

my_array[1] = "something" ;
my_array[4] = "no 2 or 3";


No, it will not.
PointedEars
Feb 7 '06 #5
Thomas 'PointedEars' Lahn said the following on 2/6/2006 10:39 AM:
Randy Webb wrote:
Fabian Vilers said the following on 2/6/2006 7:48 AM:
var my_array = new Array();
// populate array
var my_array_length = my_array.length

for (i = 0; index < my_array_length ; index++)
{
// do something with my_array[index]
}

That one will fail if the array is what is called "sparse" where every
element is not defined:

my_array[1] = "something" ;
my_array[4] = "no 2 or 3";


No, it will not.


Yes, it will fail in the sense that it will not do what you would think
it would do. Had it not been for your desire to be pedantic about my
response you would not have felt it necessary to point that out. What
you didn't point out was the use of different variables in the for loop
though. The i=0 in the example above is unneeded.

So, let me phrase it in a way that you might be able to understand it,
given your displayed inability to comprehend simple English:

A for-loop will not perform as expected if it is used on a sparse array.
It will loop over undefined array elements and that could possibly skew
any calculations/procedures you may attempt to perform using those array
entries.

Now, just for you, a code snippet that displays where it will "fail".

<script type="text/javascript">
var my_array = new Array()
my_array[0] = 1
my_array[1000] = 2
var my_array_length = my_array.length
var counter = 0
for (var index = 0; index < my_array_length ; index++)
{counter = counter + my_array[index]}
alert(counter)
</script>

The desired results would be 3, the actual result will be NaN.

Also, not the lack of any semi-colons at the end of any statement in my
code other than in the for loop definition.

BTW, in the future, I would appreciate it if you kept your pedantic
bullshit noise creating post to yourself.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Feb 7 '06 #6

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

Similar topics

23
3553
by: Invalid User | last post by:
While trying to print a none empty list, I accidentaly put an "else" statement with a "for" instead of "if". Here is what I had: if ( len(mylist)> 0) : for x,y in mylist: print x,y else: print "Empty list" which was supposed to be:
11
2146
by: David Morgenthaler | last post by:
How does one overide the iterator implied by the construct "for line in file:"? For example, suppose I have a file containing row,col pairs on each line, and I wish to write a subclass of file that will transform these to x,y coordinates using an affine transform. I'd like it to look something like this (but this clearly doesn't work): ...
3
2005
by: querypk | last post by:
Is there a better way to code nested for loops as far as performance is concerned. what better way can we write to improve the speed. for example: N=10000 for i in range(N): for j in range(N): do_job1 for j in range(N):
32
4605
by: Toby Newman | last post by:
At the page: http://www.strath.ac.uk/IT/Docs/Ccourse/subsection3_8_3.html#SECTION0008300000000000000 or http://tinyurl.com/4ptzs the author warns: "The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it...
109
4192
by: Neo | last post by:
Hi Folks,http://www.abarnett.demon.co.uk/tutorial.html#FASTFOR Page states:for( i=0; i<10; i++){ ... }i loops through the values 0,1,2,3,4,5,6,7,8,9 If you don't care about the order of the loop counter, you can do this instead: for( i=10; i--; ) { ... }Using this code, i loops through the values 9,8,7,6,5,4,3,2,1,0, and the loop should be...
24
8580
by: Kunal | last post by:
Hello, I need help in removing if ..else conditions inside for loops. I have used the following method but I am not sure whether it has actually helped. Below is an example to illustrate what I have used. Original code : c= 0 ; for (i=0; i<999; i++)
12
2087
by: Robbie Hatley | last post by:
I'm getting a bizarre error with this code: ... case WM_COMMAND: { switch (LOWORD(wParam)) // switch (control ID) { ... case IDC_RAIN_ENABLE_SIMPLE: {
12
2525
by: Sheldon | last post by:
Hi, I have two arrays that are of the same dimension but having 3 different values: 255, 1 or 2. I would like to set all the positions in both arrays having 255 to be equal, i.e., where one array has 255, I set the same elements in the other array to 255 and visa versa. Does anyone know how to do this without using for loops? Sincerely,
34
2663
by: Frederick Gotham | last post by:
Is the domestic usage of the C "for" loop inefficient when it comes to simple incrementation? Here's a very simple program that prints out the bit-numbers in a byte. #include <stdio.h> #include <limits.h> #include <stdlib.h> int main(void) {
4
1708
by: MDR | last post by:
Hello I have three "for" loops, two nested into the outer one and they depend on each other, like this: for (x=1; x<100; x++) { .... for (i=1; i<10; i++) {....} for (j=1; j<10; j++)
0
7693
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...
0
7917
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. ...
0
8118
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...
1
7665
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...
0
6277
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5501
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...
0
5217
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...
0
3651
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...
1
2105
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.