Optimize removing an Entity from a slice of entities

Avoid creating a new slice.
This commit is contained in:
Trevor Slocum 2021-12-09 20:16:12 -08:00
parent 3c7785e5e5
commit 5e7318e6a2
3 changed files with 11 additions and 6 deletions

4
doc.go
View File

@ -27,8 +27,8 @@ should be public (start with an uppercase letter) and may have any number of
publicly accessible data fields. They should not have any logic (i.e. game code)
within them, as all logic should be implemented within a system.
Rather than accessing components via Context.Component, using helper functions
(such as the following) helps to reduce code verbosity.
Rather than accessing components via Context.Component directly, using helper
functions (such as the following) helps to reduce code verbosity.
func Position(ctx *gohan.Context) *PositionComponent {
c, ok := ctx.Component(PositionComponentID).(*PositionComponent)

View File

@ -39,7 +39,7 @@ func (w *World) RemoveEntity(entity Entity) bool {
for i, e := range w.allEntities {
if e == entity {
w.allEntities = append(w.allEntities[:i], w.allEntities[i+1:]...)
w.allEntities = _removeAt(w.allEntities, i)
// Remove components.
for i := range w.components[entity] {
@ -64,3 +64,8 @@ func (w *World) CurrentEntities() int {
}
return numEntities
}
func _removeAt(v []Entity, i int) []Entity {
v[i] = v[len(v)-1]
return v[:len(v)-1]
}

View File

@ -179,7 +179,7 @@ func (w *World) _handleRemovedEntities() {
for i := range w.systemEntities {
for j, e := range w.systemEntities[i] {
if e == entity {
w.systemEntities[i] = append(w.systemEntities[i][:j], w.systemEntities[i][j+1:]...)
w.systemEntities[i] = _removeAt(w.systemEntities[i], j)
w.systemComponents[i][entity] = w.systemComponents[i][entity][:0] // TODO Could this lead to memory issues?
continue REMOVED
}
@ -252,7 +252,7 @@ func (w *World) _handleModifiedEntities() {
}
} else if systemEntityIndex != -1 {
// Detach from system.
w.systemEntities[i] = append(w.systemEntities[i][:systemEntityIndex], w.systemEntities[i][systemEntityIndex+1:]...)
w.systemEntities[i] = _removeAt(w.systemEntities[i], systemEntityIndex)
w.systemComponents[i][entity] = w.systemComponents[i][entity][:0] // TODO Could this lead to memory issues?
}
@ -402,7 +402,7 @@ func uniqueComponentIDs(v []ComponentID) []ComponentID {
return list
}
// Preallocate creates and immediately removes the specified number of entities.
// Preallocate creates and then immediately removes the specified number of entities.
// Because Gohan reuses removed entities, this has the effect of pre-allocating
// the memory used later to create entities normally. Pre-allocating enough
// entities to run your application after its systems has been added, but