Which is faster? (Object properties)

3 posts (showing 1-3)

Market Level 8Community Level 12
3259 posts

When it comes to iterating through ALOT of objects and their properties, which style do you think is faster?

var a:myobject;
a = myobjects[i];
a.b = 1;
a.c = 2;


myobjects[i].b = 1;
myobjects[i].c = 2;

Thanks for your thoughts.

posted 2015-10-03T06:39:48-07:00

Market Level 3Community Level 4
209 posts

I think the first method may be slightly faster if you declare the "a" variable outside the loop.
Also if you're using Arrays - switch them to Vectors.

posted 2015-10-03T07:19:50-07:00 | edited 2015-10-03T07:22:29-07:00

Market Level 4Community Level 7
970 posts

Iirc the faster way is often a "system" approach.  A basic example with two systems, a and b:

b[i] = 1;
c[i] = 2;

With this approach "myobjects" is not needed at all (it is replaced by the programmer knowing the relationship between the systems corresponds to the array position).  The benefit is that the corresponding property lookup and assignment overheads are removed entirely.  For non basic types, each system can contain it's own logic, relating to inter-system methods (which can be very performant), or cross-system methods (less so).  We're talking lots of statics and embedded dependencies.

To an OOP mind it's not very friendly to work with!?

So I'd usually go with the local variable assignment (your first option), because it saves subsequent lookups.  Importantly, as FourmartGames says, to avoid GC, remember to put the initiation of the local variable before the loop (not inside the loop).  With Haxe that's done for us automatically with the "for in" loop.

posted 2015-10-03T17:12:16-07:00 | edited 2015-10-03T17:13:11-07:00