Well, you have to keep in mind that not all arrays will be as
"structured" as yours.
with an array like [1=>4,5=>3,"foo"=>4], your iteration won't work. In
fact, yours will only work for arrays with sequential numeric keys. If
that is the array that you have, a for loop might be the best way to
go. If you are trying to iterate through an array of unknown objects/
items, the each function is your way to go.

-Daniel

On Apr 24, 3:24 am, "Magnus O." <mag...@magnusottosson.se> wrote:
> Hi!
>
> I saw that the jQuery.each function iterates over the array like this:
>
> for ( name in object){}
>
> From what I read this is one of the slowest ways of iterating over an
> array in js.
>
> I made a very simple test like:
>
>                                 var array = [];
>                                 for (var i = 0; i < 1000000; i++)
>                                         array[i] = Math.random();
>
>                                 var t = new Array();
>
> //Start jquery.each test
>                                 var start = (new Date).getTime();
>                                 $(array).each(function() {
>                                         t.push(this);
>                                 });
>                                 alert((new Date).getTime() - start);
>
>                                 t = new Array();
>
> //Start another iteraton way test
>                                 start = (new Date).getTime();
>                                 var i = array.length;
>                                 while (i--) {
>                                         t.push(array[i]);
>                                 }
>                                 alert((new Date).getTime() - start);
>
> In my testbrowser the jquery.each testtime was 2378ms and the other
> test was 110ms. This is a big difference. I know this test was very
> easy bit it still shows that the each function could be made faster?
>
> Is there any reason why the for ( name in object){} way of iterating
> an array is used? Is this the most optimized way of iteration an
> array?
>
> //Magnus

Reply via email to