On Wed, Mar 9, 2011 at 5:46 PM, Sean Kinsey <[email protected]> wrote:
>
>
> On Wednesday, March 9, 2011 5:06:52 PM UTC+1, Stamen Georgiev wrote:
>>
>> Just wrote a small test at jsperf for testing a for loop to iterate an
>> array of objects: http://jsperf.com/if-with-i
>>
>> Can somebody explain why there's such a big speed difference between
>> the two methods in Chrome and Safari?
>> The results are almost identical in FF (11,074 vs 12,943 ops).
>>
>> But in Chrome I get 60,266 vs 9,494 ops and in Safari: 18,343 vs 9,509
>> ops.
>>
>> As far as I can tell, trying to access an element of array that
>> doesn't exist is kinda slow... but why? :-)
>
> The test you point to really doesn't test the difference between caching the
> length property or not, the loops structure are completely different, one
> executing an AssignmentExpression in the ForExpression, and the other
> reading the value of a Property in the ForExpression and executing the
> AssignmentExpression in the loops body - it might seem trivial, but for the
> runtime, these are not interchangeable due to optimization and so on.
> But the answer is really just that the two browser use different runtimes,
> and so they have different strategies to executing code - one might be
> fastest at one kind of operation, while the other is fastest on another.
> If you want the fastest loop, do this:
>
> var i, obj, name;
> while (obj = arr[i++]) {
>  name = obj.name;
> }
>

Agree, that's the fastest way to loop over an array ( while > for ) !

Some browser will optimize a pre-increment too:

var i = -1, obj, name;
while (obj = arr[++i]) {
 name = obj.name;
}

--
Diego


> It's a whole lot faster (http://jsperf.com/if-with-i/4) due to only having a
> single expression to execute in the control section (`for` having two) with
> the optimization this allows for.
>
> Sean
>
> --
> To view archived discussions from the original JSMentors Mailman list:
> http://www.mail-archive.com/[email protected]/
>
> To search via a non-Google archive, visit here:
> http://www.mail-archive.com/[email protected]/
>
> To unsubscribe from this group, send email to
> [email protected]
>

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to