Optimization for objectloop(o of class Monk)

I’m at the point now of trying to optimize for speed for the z3-build of my game.

Is it correct to assume that:

objectloop(o ofclass Monk) if (o has some_flag)

loads every object in the game into memory to see if they have that class? or does the class know what its members are and only loops over them?

If it loads all objects, I assume it’s much better to create a static array, “allMonks”, and loop over just that?

I believe that is correct. Inform 7 makes a linked list for each class to optimize this sort of loop, but Inform 6 values space more than time, so it doesn’t by default. It looks like o ofclass Monk simply runs through o’s property 2 (an additive property holding class objects) to see if Monk is listed in it, and this needs to be done for every o.

2 Likes

I believe the only time the Inform 6 compiler does not compile objectloop into a loop over all objects, is for the special case objectloop(x in y).

Any deviation from this pattern will make it loop over all objects, including this: objectloop(x in y && x has light)

2 Likes

And, as such, @frederik, I imagine much better would be:

objectloop (x in y) {
  if (x has light) …

since that would use the optimized version.

Thanks, @Draconis and @fredrik !

1 Like

Yep! Dialog is marginally better: it optimizes objectloop (x in y) and objectloop (x has y), and tries to compile more elaborate loops into one of those two forms. If there’s some property that never changes at runtime, for example, Dialog will try to turn it into an attribute so it can use the second form. But in the general case, it’s always looping over all objects in the game; there’s just no better way on the Z-machine.

1 Like