CPU 100% on a Loop while retrieving form values

K

Kant

Hi,

i have a simple problem. i have a form with a lot's of number of Text
and Hidden Fields. I just do a simple loop to get each value for each
attribute. I have about more than 2000.

if i do something simple like :

for (var i=0; i<2000; i++)
aValue = i+10;

it runs well. But if i do something like
for (var i=0; i<2000; i++)
aValue = document.myForm.elements.value;

it gives me 100% CPU for a long time before i submit the form.

Cheers,

Kant.
 
R

Richard Cornford

Kant said:
i have a simple problem. i have a form with a lot's of number
of Text and Hidden Fields. I just do a simple loop to get each
value for each attribute. I have about more than 2000.

if i do something simple like :

for (var i=0; i<2000; i++)
aValue = i+10;

it runs well. But if i do something like
for (var i=0; i<2000; i++)
aValue = document.myForm.elements.value;

it gives me 100% CPU for a long time before i submit the form.


It is very inefficient to resolve document.myForm.elements 2000 times.
Compare it with:-

var els = document.forms['myForm'].elements;
for(var c = 0; c < 2000;c++){
aValue = els[c].value;
}

But looking up properties on 2000 object is going to be relatively slow
however you do it.

Richard.
 
L

Lee

Kant said:
Hi,

i have a simple problem. i have a form with a lot's of number of Text
and Hidden Fields. I just do a simple loop to get each value for each
attribute. I have about more than 2000.

if i do something simple like :

for (var i=0; i<2000; i++)
aValue = i+10;

it runs well. But if i do something like
for (var i=0; i<2000; i++)
aValue = document.myForm.elements.value;

it gives me 100% CPU for a long time before i submit the form.


Move as much as possible to outside the loop:

var myElements=document.myForm.elements;
for(var i=0;i<2000;i++){
aValue=myElements.value;
}

Slightly more efficient, but probably not practical in whatever
you're really doing:

var myElements=document.myForm.elements;
for(var i=0;i<2000;aValue=myElements[i++].value);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top