0

I have an Entity Component System written in ES7. I would like to minimize its memory usage. Because lots of those entities in the system are very similar, they share the references to components that are 'same'. I call them component prototypes.

There is a problem however. I want to be able to change the components data for one entity, without affecting other entities.

They share same reference to the component's object. I understand that I will have to make a copy of the data and change the component reference to that copy, when I want to make the change to shared component, but I would like to do this automatically.

class Entity {
 // get component // prop getter - read from reference
 // set component // clone the data
}

class Component {
   data = 'test'
}

let component = new Components()

let entity1 = new Entity()
let entity2 = new Entity()

entity1.component = component
entity2.component = component // shared entity

entity2.component.data = 'test2' // now the entity should clone the component

Any ideas how to achieve that? Thank you for any hints.

Libor Max
  • 1
  • 1

2 Answers2

0

I think you can return a defaultComponent object before the real one is set

const defaultComponent = {
 foo: 'bar',
  x: 1,
  y: 1
}

class Test {
 get component() {
   return this._component || defaultComponent
  }
  set component(c) {
   this._component = c
  }
}

const a = new Test()
console.log(a.component)
a.component = { ...defaultComponent }
a.component.x = 3
a.component.foo = 'derp'
console.log(a.component)

But do you think this kind of optimization really worth it?

George
  • 988
  • 2
  • 10
  • 25
0

You can leverage JavaScript's prototypal inheritance, substituting the existing component with an inheriting object, like this:

entity2.component = Object.create(component) // extend the base prototype
entity2.component.data = 'test2' // other components don't inherit this change

Beware though that, since you are using classes (which are a somewhat "opinionated" syntactic sugar over prototypal inheritance) this method could potentially interact in strage ways with your existing code.

Marco Bolis
  • 1,222
  • 2
  • 15
  • 31