Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #21305 > unrolled thread

loop through an arry

Started by"Tony Johansson" <johansson.andersson@telia.com>
First post2013-09-12 23:19 +0200
Last post2013-09-13 17:06 -0700
Articles 13 — 7 participants

Back to article view | Back to comp.lang.javascript


Contents

  loop through an arry "Tony Johansson" <johansson.andersson@telia.com> - 2013-09-12 23:19 +0200
    Re: loop through an arry Adrián Espinosa <mortuuslordofdeads@gmail.com> - 2013-09-12 14:30 -0700
      Re: loop through an arry Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-09-13 03:17 +0200
        Re: loop through an arry Stefan Weiss <krewecherl@gmail.com> - 2013-09-13 04:27 +0200
          Re: loop through an arry Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-09-13 05:23 +0200
            Re: loop through an arry Stefan Weiss <krewecherl@gmail.com> - 2013-09-13 05:36 +0200
        Re: loop through an arry "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2013-09-13 09:48 +0200
    Re: loop through an arry Ken <usenet-so@abdiassoftware.com> - 2013-09-12 16:35 -0500
      Re: loop through an arry Daniel Pitts <newsgroup.nospam@virtualinfinity.net> - 2013-09-12 16:39 -0700
        Re: loop through an arry Ken <usenet-so@abdiassoftware.com> - 2013-09-12 19:45 -0500
          Re: loop through an arry Daniel Pitts <newsgroup.nospam@virtualinfinity.net> - 2013-09-13 11:18 -0700
            Re: loop through an arry Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-09-14 01:49 +0200
              Re: loop through an arry Daniel Pitts <newsgroup.nospam@virtualinfinity.net> - 2013-09-13 17:06 -0700

#21305 — loop through an arry

From"Tony Johansson" <johansson.andersson@telia.com>
Date2013-09-12 23:19 +0200
Subjectloop through an arry
Message-ID<l0tb6o$8a5$1@dont-email.me>
I just wonder because I have seen this in a book

The book alternative
var length = theArray.length;  //get the array's length one before loop
for(var i = 0; i  < length; i++)
   total += theArray[i];

My alternative
I would have written this like this instead and I don't see any problem with 
that.
for(var i = 0; i  < theArray.length; i++)
   total += theArray[i];

My question I can't see any point to use the alternative that the book 
suggest.
I prefer my alternatives.

//Tony 

[toc] | [next] | [standalone]


#21306

FromAdrián Espinosa <mortuuslordofdeads@gmail.com>
Date2013-09-12 14:30 -0700
Message-ID<b7567773-4470-4827-b2a2-3e1057c303fe@googlegroups.com>
In reply to#21305
On Thursday, September 12, 2013 11:19:59 PM UTC+2, Tony Johansson wrote:
> I just wonder because I have seen this in a book
> 
> 
> 
> The book alternative
> 
> var length = theArray.length;  //get the array's length one before loop
> 
> for(var i = 0; i  < length; i++)
> 
>    total += theArray[i];
> 
> 
> 
> My alternative
> 
> I would have written this like this instead and I don't see any problem with 
> 
> that.
> 
> for(var i = 0; i  < theArray.length; i++)
> 
>    total += theArray[i];
> 
> 
> 
> My question I can't see any point to use the alternative that the book 
> 
> suggest.
> 
> I prefer my alternatives.
> 
> 
> 
> //Tony


On a moderated size array I think you wouldn't notice the difference, but on a larger one, in your alternative you are getting the length directly from the object, which has more overhead than getting the value from a stored one. I can't extend more on this, because I read it sometime ago. Maybe someone can clarify my explanation or tell us if I'm completely wrong.

[toc] | [prev] | [next] | [standalone]


#21314

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2013-09-13 03:17 +0200
Message-ID<2406331.xsRxLlKTau@PointedEars.de>
In reply to#21306
Adrián Espinosa wrote:

> On Thursday, September 12, 2013 11:19:59 PM UTC+2, Tony Johansson wrote:
>> I just wonder because I have seen this in a book
>> 
>> The book alternative
>> 
>> var length = theArray.length;  //get the array's length one before loop
>> 
>> for(var i = 0; i  < length; i++)
>> 
>>    total += theArray[i];
>> 
>> My alternative
>> 
>> I would have written this like this instead and I don't see any problem
>> with
>> 
>> that.
>> 
>> for(var i = 0; i  < theArray.length; i++)
>> 
>>    total += theArray[i];
>> 
>> My question I can't see any point to use the alternative that the book
>> suggest.
>> 
>> I prefer my alternatives.
> 
> On a moderated size array I think you wouldn't notice the difference, but
> on a larger one, in your alternative you are getting the length directly
> from the object, which has more overhead than getting the value from a
> stored one. I can't extend more on this, because I read it sometime ago.
> Maybe someone can clarify my explanation or tell us if I'm completely
> wrong.

We have discussed this here numerous times before.  You would be well-
advised to search any newsgroup archives that are available to you (Google 
Groups, being based on the DejaNews archive, still does a good job at that) 
before you post.  In summary:

If “theArray” refers to an Array instance, the size of the array does not 
matter.  At least for Array instances, the value of the “length” property is 
_not_ recalculated on read access, it is set on write access.  (As specified 
in ECMAScript Ed. 5.1, section 15.4, and in previous Editions, the “length” 
property of Array instances yields the index of the last element plus one, 
not necessarily the number of elements in the array.  This is different for 
NodeLists and HTMLCollections.)

What matters is the unnecessary repeated property access when the property 
value does not change.  As a result, the “book alternative” (which IIRC were 
suggested here almost a decade ago, perhaps even by me) is considerably 
faster.  The only caveat is that you have to be reasonably sure that the 
“length” of the array-like object does not change in-between.  This may not 
be true for Array instances for which there are publicly accessible 
references, and it may not be true for NodeLists and HTMLCollections.  If 
you cannot be sure of that, you should either handle the consequences, or 
use the slower approach.

-- 
PointedEars

Twitter: @PointedEars2
Please do not Cc: me. / Bitte keine Kopien per E-Mail.

[toc] | [prev] | [next] | [standalone]


#21316

FromStefan Weiss <krewecherl@gmail.com>
Date2013-09-13 04:27 +0200
Message-ID<l0tt67$ge1$1@news.albasani.net>
In reply to#21314
On 2013-09-13 03:17, Thomas 'PointedEars' Lahn wrote:
> What matters is the unnecessary repeated property access when the property 
> value does not change.  As a result, the “book alternative” (which IIRC were 
> suggested here almost a decade ago, perhaps even by me) is considerably 
> faster.

Caveats about changing array lengths during the course of a loop aside,
what matters most is the implementation. Practically all modern JS
engines contain optimizations for the uncached alternative. In some rare
cases, they even test faster when array.length is (supposedly) checked
on each iteration. There are hundreds of tests about this on jsperf.com,
if you're curious.

But we cannot be sure that the client engine - or the host object we're
iterating over - is sufficiently optimized in all cases. Caching the
array length in a variable doesn't hurt (performance or readability), so
I usually go for the "book alternative", too.

If the expected length of the array is lower than, say, 100, it hardly
matters anyway. Use whatever style suits you.

- stefan

[toc] | [prev] | [next] | [standalone]


#21319

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2013-09-13 05:23 +0200
Message-ID<7605845.zP1Jr4sAA4@PointedEars.de>
In reply to#21316
Stefan Weiss wrote:

> On 2013-09-13 03:17, Thomas 'PointedEars' Lahn wrote:
>> What matters is the unnecessary repeated property access when the
>> property value does not change.  As a result, the “book alternative”
>> (which IIRC were suggested here almost a decade ago, perhaps even by me)
>> is considerably faster.
> 
> Caveats about changing array lengths during the course of a loop aside,
> what matters most is the implementation. Practically all modern JS
> engines contain optimizations for the uncached alternative. In some rare
> cases, they even test faster when array.length is (supposedly) checked
> on each iteration. There are hundreds of tests about this on jsperf.com,
> if you're curious.

This nonsense has already been disproved.  You are not paying attention.

-- 
PointedEars

Twitter: @PointedEars2
Please do not Cc: me. / Bitte keine Kopien per E-Mail.

[toc] | [prev] | [next] | [standalone]


#21321

FromStefan Weiss <krewecherl@gmail.com>
Date2013-09-13 05:36 +0200
Message-ID<l0u17s$b4n$1@news.albasani.net>
In reply to#21319
On 2013-09-13 05:23, Thomas 'PointedEars' Lahn wrote:
> Stefan Weiss wrote:
>> Caveats about changing array lengths during the course of a loop aside,
>> what matters most is the implementation. Practically all modern JS
>> engines contain optimizations for the uncached alternative. In some rare
>> cases, they even test faster when array.length is (supposedly) checked
>> on each iteration. There are hundreds of tests about this on jsperf.com,
>> if you're curious.
> 
> This nonsense has already been disproved.  You are not paying attention.

Care to give a citation for the disproval?

- stefan

[toc] | [prev] | [next] | [standalone]


#21322

From"Evertjan." <exxjxw.hannivoort@inter.nl.net>
Date2013-09-13 09:48 +0200
Message-ID<XnsA23A63C5037FAeejj99@194.109.133.133>
In reply to#21314
Thomas 'PointedEars' Lahn wrote on 13 sep 2013 in comp.lang.javascript:

> You would be well-
> advised to search any newsgroup archives that are available to you
> (Google Groups, being based on the DejaNews archive, still does a good
> job at that) before you post. 

Better try:

<http://www.dejanews.com>

-- 
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

[toc] | [prev] | [next] | [standalone]


#21307

FromKen <usenet-so@abdiassoftware.com>
Date2013-09-12 16:35 -0500
Message-ID<l0tc62$3pr$1@speranza.aioe.org>
In reply to#21305
On 12.09.2013 16:19, Tony Johansson wrote:> I just wonder because I have 
seen this in a book
 >
 > The book alternative
 > var length = theArray.length;  //get the array's length one before loop
 > for(var i = 0; i  < length; i++)
 >
 > My alternative
 > for(var i = 0; i  < theArray.length; i++)
 >
 > My question I can't see any point to use the alternative that the book
 > suggest.
 > I prefer my alternatives.

It executes faster as it caches the length value to a local scoped 
variable. Othwerwise, for each iteration (related to being a dynamic 
language), the interpreter needs to first lookup theArray and then 
length from theArray. By caching the value to a variable first it only 
needs to look up that variable.

However, this was more a "noticeable" thing in the past. Current 
browsers are capable of optmizing this pretty good and unless you really 
need to squeeze out all you can of the browser (which in case you would 
use a *while* loop in any case) there is no real problem using your 
approach.


-- 
Ken Fyrstenberg
Abdias Software
http://abdiassoftware.com/
(remove usenet- from address)

[toc] | [prev] | [next] | [standalone]


#21310

FromDaniel Pitts <newsgroup.nospam@virtualinfinity.net>
Date2013-09-12 16:39 -0700
Message-ID<GgsYt.30492$VU.28941@fx05.iad>
In reply to#21307
On 9/12/13 2:35 PM, Ken wrote:
> On 12.09.2013 16:19, Tony Johansson wrote:> I just wonder because I have
> seen this in a book
>  >
>  > The book alternative
>  > var length = theArray.length;  //get the array's length one before loop
>  > for(var i = 0; i  < length; i++)
>  >
>  > My alternative
>  > for(var i = 0; i  < theArray.length; i++)
>  >
>  > My question I can't see any point to use the alternative that the book
>  > suggest.
>  > I prefer my alternatives.
>
> It executes faster as it caches the length value to a local scoped
> variable. Othwerwise, for each iteration (related to being a dynamic
> language), the interpreter needs to first lookup theArray and then
> length from theArray. By caching the value to a variable first it only
> needs to look up that variable.
>
> However, this was more a "noticeable" thing in the past. Current
> browsers are capable of optmizing this pretty good and unless you really
> need to squeeze out all you can of the browser (which in case you would
> use a *while* loop in any case) there is no real problem using your
> approach.
>
>
while and for loops should be identical in performance. They are merely 
different syntax for the same operations.

[toc] | [prev] | [next] | [standalone]


#21313

FromKen <usenet-so@abdiassoftware.com>
Date2013-09-12 19:45 -0500
Message-ID<l0tnar$rnh$1@speranza.aioe.org>
In reply to#21310
On 12.09.2013 18:39, Daniel Pitts wrote:
> On 9/12/13 2:35 PM, Ken wrote:
>> need to squeeze out all you can of the browser (which in case you would
>> use a *while* loop in any case) there is no real problem using your
>> approach.
> while and for loops should be identical in performance. They are merely
> different syntax for the same operations.

Well.. it do depend on browser and implementation (such as JIT) but in 
general while loops are faster as seen here (with most browsers):

http://jsperf.com/fastest-array-loops-in-javascript/32

Disclaimer: I didn't make the test.

-- 
Ken Fyrstenberg
Abdias Software
http://abdiassoftware.com/
(remove usenet- from address)

[toc] | [prev] | [next] | [standalone]


#21330

FromDaniel Pitts <newsgroup.nospam@virtualinfinity.net>
Date2013-09-13 11:18 -0700
Message-ID<PFIYt.44777$dJ2.1784@fx30.iad>
In reply to#21313
On 9/12/13 5:45 PM, Ken wrote:
> On 12.09.2013 18:39, Daniel Pitts wrote:
>> On 9/12/13 2:35 PM, Ken wrote:
>>> need to squeeze out all you can of the browser (which in case you would
>>> use a *while* loop in any case) there is no real problem using your
>>> approach.
>> while and for loops should be identical in performance. They are merely
>> different syntax for the same operations.
>
> Well.. it do depend on browser and implementation (such as JIT) but in
> general while loops are faster as seen here (with most browsers):
>
> http://jsperf.com/fastest-array-loops-in-javascript/32
>
> Disclaimer: I didn't make the test.
>

So many of those tests are flawed. They don't even perform the same 
operation!

Anyway, for my browser, the fastest one was a test I created using a for 
loop:

for (var l = arr.length; l--;) {
   someFn(arr[l]);
}


The second fastest one was a loop that was already there using a while loop:

var l = arr.length;
while(l--) {
   someFn(arr[l]);
}

The difference in speed was close to the margin-of-error, so they are 
practically equivalent.

Testing in Chrome 29.0.1547.65 on OS X 10.8.4

[toc] | [prev] | [next] | [standalone]


#21335

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2013-09-14 01:49 +0200
Message-ID<1553168.V9fml2jhPD@PointedEars.de>
In reply to#21330
Daniel Pitts wrote:

> On 9/12/13 5:45 PM, Ken wrote:
>> On 12.09.2013 18:39, Daniel Pitts wrote:
>>> On 9/12/13 2:35 PM, Ken wrote:
>>>> need to squeeze out all you can of the browser (which in case you would
>>>> use a *while* loop in any case) there is no real problem using your
>>>> approach.
>>> while and for loops should be identical in performance. They are merely
>>> different syntax for the same operations.
>>
>> Well.. it do depend on browser and implementation (such as JIT) but in
>> general while loops are faster as seen here (with most browsers):
>>
>> http://jsperf.com/fastest-array-loops-in-javascript/32
>>
>> Disclaimer: I didn't make the test.
> 
> So many of those tests are flawed. They don't even perform the same
> operation!

ACK.

> Anyway, for my browser, the fastest one was a test I created using a for
> loop:
> 
> for (var l = arr.length; l--;) {
>    someFn(arr[l]);
> }

I expected this; I have recommended this approach before (where reverse 
order is acceptable).  Those are, after all, the fewest operations.

> The second fastest one was a loop that was already there using a while
> loop:
> 
> var l = arr.length;
> while(l--) {
>    someFn(arr[l]);
> }
> 
> The difference in speed was close to the margin-of-error, so they are
> practically equivalent.

That is because they are compiled to the same bytecode or native code.
In pseudo-bytecode:

-------------------------------------------
line   #  operation    return  operands
-------------------------------------------
   1   0  DECL_VAR        $0   "l"
       1  FETCH_VAR       $1   "arr"
       2  FETCH_OBJ_R     $2   $1, "length"
       3  ASSIGN          $3   $0, $2
   2   4  FETCH_VAR       $4   $0
       5  JMPZ                 $4, ->13
       6  POST_DEC        $6   $0
   3   7  FETCH_VAR       $7   $1
       8  FETCH_VAR       $8   $0
       9  FETCH_OBJ_R     $9   $7, $8
      10  FETCH_VAR       $10  "someFn"
      11  CALL_FUNC       $11  $10, $9
      12  JMP                  ->4
      13  RETURN               0
-------------------------------------------

The “for” statement only differ from the “while” statement in that the 
operations #0 to #6 are produced by the same line.
 
> Testing in Chrome 29.0.1547.65 on OS X 10.8.4

Thanks.

-- 
PointedEars

Twitter: @PointedEars2
Please do not Cc: me. / Bitte keine Kopien per E-Mail.

[toc] | [prev] | [next] | [standalone]


#21338

FromDaniel Pitts <newsgroup.nospam@virtualinfinity.net>
Date2013-09-13 17:06 -0700
Message-ID<lMNYt.63969$La6.4169@fx04.iad>
In reply to#21335
On 9/13/13 4:49 PM, Thomas 'PointedEars' Lahn wrote:
>
> That is because they are compiled to the same bytecode or native code.
> In pseudo-bytecode:
>
> -------------------------------------------
> line   #  operation    return  operands
> -------------------------------------------
>     1   0  DECL_VAR        $0   "l"
>         1  FETCH_VAR       $1   "arr"
>         2  FETCH_OBJ_R     $2   $1, "length"
>         3  ASSIGN          $3   $0, $2
>     2   4  FETCH_VAR       $4   $0
>         5  JMPZ                 $4, ->13
>         6  POST_DEC        $6   $0
>     3   7  FETCH_VAR       $7   $1
>         8  FETCH_VAR       $8   $0
>         9  FETCH_OBJ_R     $9   $7, $8
>        10  FETCH_VAR       $10  "someFn"
>        11  CALL_FUNC       $11  $10, $9
>        12  JMP                  ->4
>        13  RETURN               0
> -------------------------------------------
>
> The “for” statement only differ from the “while” statement in that the
> operations #0 to #6 are produced by the same line.

Indeed, my point was that equivalent for/while loops are indeed the 
same. Any difference in them is because you didn't make them behave same ;-)


[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.javascript


csiph-web