You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Change ResourceEntities from SparseSet to SparseArray to speed up resource lookups (#23616)
# Objective
Reduce memory usage for resources, and maybe improve performance of
resource lookups.
Related to #23039, but not a solution.
## Solution
Change `ResourceEntities` from a `SparseSet` to a `SparseArray`.
`SparseArray` is `pub (crate)`, so simply exposing it through `Deref`
would cause privacy errors. Instead, remove the `Deref` impl and add
wrapper methods for `iter`, `get`, and `remove`. Change the return types
from `&Entity` to `Entity` now that they aren't generic.
As background: A `SparseArray` is a simple `Vec<Option<V>>`, while a
`SparseSet` is a `SparseArray` that maps keys to dense indexes, combined
with dense arrays of keys and values. That requires a second array
operation to find the actual value, but can be much better for memory
usage when the values are large, since missing items only take up space
for a single index instead of an entire value.
But the values in `ResourceEntities` are `Entity`, which are already
small! A `SparseArray` will always be smaller on 64-bit systems, since
an `Entity` is the same size as a `usize`, and we don't need to store
the additional `dense` and `indices` arrays. So switching to
`SparseArray` will save a lookup *and* save memory.
One drawback is that we can no longer use the dense lists to iterate all
resources, so methods like `iter_resources` now need to scan all
component ids. I don't expect this to be a problem in practice, though.
`iter_resources` is rarely used, and O(components) isn't all that much
worse than O(resources). If it turns out to be an issue, it's also
possible to recover this data by querying the `IsResource` component.
## Testing
Inconclusive.
I attempted to run benchmarks, both `bevymark` as in the linked issue
and `cargo bench -p benches --bench ecs`, but the results were too noisy
on my machine to reach any conclusions. And now that I look more
closely, we don't have many benches that even use resources!
---------
Co-authored-by: Kevin Chen <chen.kevin.f@gmail.com>
0 commit comments