PDA

View Full Version : Reading Array.length inside a loop


cheesebagpipe
03-15-2003, 01:22 AM
Could someone explain this?

for (i=0; i<SomeArray.length; ++i)...

vs.

var SomeArrayLength = SomeArray.length;
for (i=0; i<SomeArrayLength; ++i)...

I've seen it posted - on this very board - that the second alternative is considered more efficient programming. Was wondering why...don't both approaches simply read a static property value (Array.length vs. function_call_object.SomeArrayLength)? Why would one be more efficient than the other?

Jason
03-15-2003, 02:06 AM
true they are both static but the second version where the value is stored before the loop means that the system wont have to make that call everytime for a check. Where if the value is stored it is now a local variable and can be accessed quicker. Does that help?


Jason

cheesebagpipe
03-15-2003, 10:24 PM
That's my point: why should accessing a local variable - it's just an object property - be 'quicker' than accessing another object property (Array.length)? The system has to check on each iteration anyway since data is data, and it has to be stored somewhere. If 'length' was 'length()' it'd make sense (the overhead involved in calling a method) but it's just a variable. Still confused...

jkd
03-16-2003, 12:04 AM
Think of "length" as a getter method and not a property, as JS Arrays are really vectors, so they have variable sizes.

cheesebagpipe
03-16-2003, 12:21 AM
Thanks jkd! ;) Just the thing I was looking for. Did a google search on 'array' & 'vector' and got a quick education in the relevant programming concepts...found this (http://www.crockford.com/#javascript) as well, very useful page.