[SOLVED] Optimizing the project and using update()

For example, we have 100 entities, in update() method of which some code is executed:

SomeEntity.prototype.update = function (dt) {
    // Some code
};

This is good?
Or do I need to use a controller and call customUpdate() from there?

EntitiesControl.prototype.initialize = function () {
    // Store links to scripts before
    this.entitiesData[i].script = newEntity.script.entityControl;
};

EntitiesControl.prototype.update = function (dt) {
    for (let i = 0; i < this.maxEntities; i++) {
        const entityData = this.entitiesData[i];
        if (entityData) {
            entityData.script.customUpdate(dt);
        }
    }
};

SomeEntity.prototype.customUpdate = function (dt) {
    // Some code
};

As you can see, the idea is that there is no own update() for each entity instance.

P.S. I’m also a Unity3D programmer., and it’s bad practice for each entity to use its own Update().

Hi @SARJ,

I would say that in both cases calling the method can be equally fast.

What will be slightly slower and use more memory is having each entity spawn an instance of the script in question. But I’d say that is a micro optimization and in some cases keeping an OOP approach in favor of maintenance and a better coding paradigm is preferred.

But if you are indeed looking for getting that extra ms from your code then looking at an entity component system, ECS (not to be confused with PlayCanvas entities) can help.

On another note, here is another version of your code that will be faster to call if you are looping a lot of entities:

const maxEntities = this.maxEntities;
const entitiesData = this.entitiesData;

    for (let i = 0; i < maxEntities; i++) {
        const entityData = entitiesData[i];
        if (entityData) {
            entityData.script.customUpdate(dt);
        }
    }

The idea is that member property accessors can have a slight performance hit if you are looping like that in real time.

Hope that helps!

2 Likes

Yes, this information will help me in development. Thanks.

1 Like