473,785 Members | 2,619 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

for in to iterate sparse Array

Hi,

I know that using for in loop to iterate over array elements is a bad
idea but I have a situation where it is tempting me to use it. I have
a two dimensional sparse array say "arr" which will have length to be
some 50 but will have some elements like arr[1], arr[10], arr[23] at
random locations. Each of these elements is again an array (since it
is two dimensional) say arr[1][30], arr[1][24] & so on for arr[10 &
23] also. Currently I've coded it like this:

for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (arr[i] && arr[i][j]) {
// do stuff with arr[i][j]
}
}
}

but i am tempted to do following

for (var i in arr) {
if (!arr.hasOwnPro perty(i)) {
continue;
}
for (var j in arr[i]) {
if (arr[i].hasOwnProperty (j)) {
// do stuff with arr[i][j]
}
}
}

thinking it to be faster. What are your views?

Thanks,
Manish
(http://manishtomar.blogspot.com)

Jul 10 '07 #1
5 2482
Manish Tomar wrote:
Hi,

I know that using for in loop to iterate over array elements is a bad
idea but I have a situation where it is tempting me to use it. I have
a two dimensional sparse array say "arr" which will have length to be
some 50 but will have some elements like arr[1], arr[10], arr[23] at
random locations. Each of these elements is again an array (since it
is two dimensional) say arr[1][30], arr[1][24] & so on for arr[10 &
23] also. Currently I've coded it like this:

for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (arr[i] && arr[i][j]) {
// do stuff with arr[i][j]
}
}
}

but i am tempted to do following

for (var i in arr) {
if (!arr.hasOwnPro perty(i)) {
continue;
}
for (var j in arr[i]) {
if (arr[i].hasOwnProperty (j)) {
// do stuff with arr[i][j]
}
}
}

thinking it to be faster. What are your views?
The issues with using for..in to iterate over an array are:

1. It usually indicates that a plain object should have been used -
this doesn't seem to apply here.

2. If Array.prototype has been exteded, you'll get it's extra
properties as well.

If your code is never used with any other library, the second issue
doesn't arise and your use of hasOwnProperty (you can also use
propertyIsEnume rable) accounts for it anyway.

Do it. :-)

--
Rob
"We shall not cease from exploration, and the end of all our
exploring will be to arrive where we started and know the
place for the first time." -- T. S. Eliot
Jul 10 '07 #2

"Manish Tomar" <ma**********@g mail.comwrote in message
news:11******** **************@ j4g2000prf.goog legroups.com...
Hi,

I know that using for in loop to iterate over array elements is a bad
idea but I have a situation where it is tempting me to use it. I have
a two dimensional sparse array say "arr" which will have length to be
some 50 but will have some elements like arr[1], arr[10], arr[23] at
random locations. Each of these elements is again an array (since it
is two dimensional) say arr[1][30], arr[1][24] & so on for arr[10 &
23] also. Currently I've coded it like this:

for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (arr[i] && arr[i][j]) {
// do stuff with arr[i][j]
}
}
}

but i am tempted to do following

for (var i in arr) {
if (!arr.hasOwnPro perty(i)) {
continue;
}
for (var j in arr[i]) {
if (arr[i].hasOwnProperty (j)) {
// do stuff with arr[i][j]
}
}
}

thinking it to be faster. What are your views?
What makes you think it would be faster? Did you benchmark it? You should
be able to speed up the first example like this:

var li = arr.length - 1;
var lj;
for (var i = li; i >= 0; i--) {
lj = arr[i].length - 1;
for (var j = lj; j >= 0; j--) {
if (arr[i] && arr[i][j]) {
// do stuff with arr[i][j]
}
}
}

I didn't test (or benchmark) this code, but I know the theory is sound.
Jul 11 '07 #3
In comp.lang.javas cript message <46************ **********@road runner.com
>, Wed, 11 Jul 2007 02:40:46, David Mark <dm***@cinsoft. netposted:

What makes you think it would be faster?
It seems rather obvious that the "in" method should be faster.
Did you benchmark it? You should
be able to speed up the first example like this:

var li = arr.length - 1;
var lj;
for (var i = li; i >= 0; i--) {
lj = arr[i].length - 1;
for (var j = lj; j >= 0; j--) {
if (arr[i] && arr[i][j]) {
// do stuff with arr[i][j]
}
}
}
>I didn't test (or benchmark) this code, but I know the theory is sound.
A pretty reliable indication of unreliable code.

That improvement will be small in comparison with that hoped for by
using the other method. But you should have been able to gain a little
more by using while loops, and by changing two lines to
if (T=arr[i] && T[j]) {
// do stuff with T
To compare the two access methods, for a simpler case :-

function F1(A) { var T=0, J = A.length, x
while (J--) if (x=A[J]) T += x
return T }
function F2(A) { var T=0, J
for (J in A) T += A[J]
return T }
a = [] ; a[999] = 1
K_ = 2000 // increase
D0_ = new Date()
Q_ = K_ ; while (Q_--) {F1(a)}
D1_ = new Date()
Q_ = K_ ; while (Q_--) {F2(a)}
D2_ = new Date()
Q_ = [D1_-D0_, D2_-D1_] // Demo 6

which gives me results like 860,15 showing that "in" is very much faster
for a very sparse array.

It's a good idea to read the newsgroup c.l.j and its FAQ. See below.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 IE 6
news:comp.lang. javascript FAQ <URL:http://www.jibbering.c om/faq/index.html>.
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 12 '07 #4
On Jul 12, 7:47 am, Dr J R Stockton <j...@merlyn.de mon.co.ukwrote:
In comp.lang.javas cript message <46947aad$0$804 6$4c368...@road runner.com
, Wed, 11 Jul 2007 02:40:46, David Mark <d...@cinsoft.n etposted:
What makes you think it would be faster?

It seems rather obvious that the "in" method should be faster.
"Should be" or "will be" in this specific case? Perhaps you can
assume that it will, but I would benchmark it first.
>
Did you benchmark it? You should
be able to speed up the first example like this:
var li = arr.length - 1;
var lj;
for (var i = li; i >= 0; i--) {
lj = arr[i].length - 1;
for (var j = lj; j >= 0; j--) {
if (arr[i] && arr[i][j]) {
// do stuff with arr[i][j]
}
}
}
I didn't test (or benchmark) this code, but I know the theory is sound.

A pretty reliable indication of unreliable code.
Are you having a laugh? That's what my disclaimer means. The idea
should be obvious from the example, but don't paste it into a
production page without testing it first. I didn't need to benchmark
it as I know the theory is sound from previous experience.
>
That improvement will be small in comparison with that hoped for by
So it will reliably speed up the process?
using the other method. But you should have been able to gain a little
more by using while loops, and by changing two lines to
if (T=arr[i] && T[j]) {
// do stuff with T
Okay.
To compare the two access methods, for a simpler case :-
There were three: the one I posted, the one I compared it to and the
"for in" loop (which I did not address at all.)
>
function F1(A) { var T=0, J = A.length, x
while (J--) if (x=A[J]) T += x
return T }
function F2(A) { var T=0, J
for (J in A) T += A[J]
return T }
a = [] ; a[999] = 1

K_ = 2000 // increase
D0_ = new Date()
Q_ = K_ ; while (Q_--) {F1(a)}
D1_ = new Date()
Q_ = K_ ; while (Q_--) {F2(a)}
D2_ = new Date()
Q_ = [D1_-D0_, D2_-D1_] // Demo 6

which gives me results like 860,15 showing that "in" is very much faster
for a very sparse array.
Yes, in this case it is faster. But will it be faster for the OP's
example? I imagine it should be.
>
It's a good idea to read the newsgroup c.l.j and its FAQ. See below.
I have read much of the latter, but haven't had time to read the
newsgroup in its entirety. FWIW, I did Google JavaScript, "for in",
Jibbering, FAQ and arrays and found nothing, save for a lot of
warnings against using this method. For example:

http://developer.mozilla.org/en/docs...ments:for...in

Is there a specific FAQ entry you are referring to?

Jul 12 '07 #5
In comp.lang.javas cript message <11************ **********@n60g 2000hse.go
oglegroups.com> , Thu, 12 Jul 2007 11:32:03, David Mark
<dm***********@ gmail.composted :
>On Jul 12, 7:47 am, Dr J R Stockton <j...@merlyn.de mon.co.ukwrote:
>In comp.lang.javas cript message <46947aad$0$804 6$4c368...@road runner.com
>, Wed, 11 Jul 2007 02:40:46, David Mark <d...@cinsoft.n etposted:
>What makes you think it would be faster?

It seems rather obvious that the "in" method should be faster.

"Should be" or "will be" in this specific case? Perhaps you can
assume that it will, but I would benchmark it first.
If I had meant "will be", I should have written "will be".
>That improvement will be small in comparison with that hoped for by

So it will reliably speed up the process?
Slightly.

>To compare the two access methods, for a simpler case :-

There were three: the one I posted, the one I compared it to and the
"for in" loop (which I did not address at all.)
The first two that you mention are basically the same method, one with a
partially-improved implementation. The OP presented two distinct
methods for comparison.

>Yes, in this case it is faster. But will it be faster for the OP's
example? I imagine it should be.
Virtually certainly. Though we don't know exactly how sparse the data
is, and we don't know for sure what properties the array may have.
Consider
var A = [0,1,2]
A.rhubarb = 6
T = 0 ; for (J=0; J<A.length; J++) T += A[J] // 3
T = 0 ; for (J in A) T += A[J] // 9
>FWIW, I did Google JavaScript, "for in",
Jibbering, FAQ and arrays and found nothing, save for a lot of
warnings against using this method. For example:

http://developer.mozilla.org/en/docs...Reference:Stat
ements:for...i n

You presumably mean the content of the yellow box? That shows that
Mozilla don't think of everything. Using for..in should be safe enough
provided that none of the warnings apply.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demo n.co.uk/clpb-faq.txt RAH Prins : c.l.p.b mFAQ;
<URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zipTimo Salmi's Turbo Pascal FAQ.
Jul 13 '07 #6

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

Similar topics

2
2213
by: deko | last post by:
I have a file that contains the output of time(). A different time is on each line of the file, and each line represents a visit to the website. I want to calculate the total visits per day, month and year. So, I dump the file into an array, and then iterate through the array testing each element and incrementing a counter for each respective time period. But what is the best way to iterate through the array? The foreach($av) does...
0
1386
by: David | last post by:
I've just recently read several articles that state that the only way to write "sparse zeros" to an NTFS5 sparse file is to use Win32 DeviceIoControl with FSCTL_SET_ZERO_DATA in order to specify what ranges in the file are sparse zeros. However, it appears that the following steps also work when creating a new sparse file. First, using Win32 (via .NET 1.1 pinvoke), I ... CreateFile (returns a handle)
5
2700
by: Martin Pöpping | last post by:
Hello, I want to iterate the second dimension of a 2-dim-array. Let´s say I have an array: double myArray and a given index: int i. Assume my index is given in want to iterate my array with something like this:
4
7648
by: deLenn | last post by:
Hi, Does scipy have an equivalent to Matlab's 'find' function, to list the indices of all nonzero elements in a sparse matrix? Cheers.
3
5845
by: mediratta | last post by:
Hi, I want to allocate memory for a large matrix, whose size will be around 2.5 million x 17000. Three fourth of its rows will have all zeroes, but it is not known which will be those rows. If I try to allocate memory for this huge array, then I get a segmentation fault saying: Program received signal SIGSEGV, Segmentation fault. 0xb7dd5226 in mallopt () from /lib/tls/i686/cmov/libc.so.6
6
3885
by: hvmclrhu | last post by:
Hi I have a big problem. When we compile serial.c with gcc, I get this error program is generating the sparse matrix Segmentation fault I think ı have to use malloc() but I don't know how to use and add this function in my program. Could you help me please? Thank you for your help... #include <stdio.h> #include <math.h>
5
9716
by: adam.kleinbaum | last post by:
Hi there, I'm a novice C programmer working with a series of large (30,000 x 30,000) sparse matrices on a Linux system using the GCC compiler. To represent and store these matrices, I'd like to implement the sparse matrices as a doubly-linked list, in which each non-zero cell is stored roughly as follows: int rownum int colnum
25
25451
RMWChaos
by: RMWChaos | last post by:
Any JSON experts out there? I'd like to know if it is possible, and if so how, to iterate through a JSON property list so that each iteration selects the next value for each object. Here is an example list: function myFunction() { createDOM({ 'id' : , 'dom' : , 'parent' : "content", 'form' : ,
4
2073
by: ishakteyran | last post by:
hello to all.. i have a realy tough assignment which requires me to add, substract, multiply, and get inverse of non-sparse and sparse matrixes.. in a more clear way it wants me to to the operations listed above between two sparse, or non-sparse or a sparse and a non-sparse matrix.. for the operations an the matrixes of same kind, say sparse matrix, it seems rather easy .. but what makes me cobfuse is how to operate a sparse with a...
0
9645
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
9481
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,...
1
10095
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
8978
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7502
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
5383
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
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3655
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2881
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.