amethyst/legion

Memory isn't freed after entity removal

redain opened this issue · 2 comments

I noticed that memory consumption slowly growing over time in one of my prototypes. Seems like after entity removing memory consumption is not decreasing.
I was able to reproduce it in a fresh new crate as well with a following code:

use legion::*;

#[derive(Default, Clone, Copy)]
pub struct Dummy {
    pub field_1: u128,
    pub field_2: u128,
    pub field_3: u128,
    pub field_4: u128,
}

fn main() {
    let mut ecs = World::default();
    loop {
        let ids = ecs.extend([(Dummy::default(),); 100].to_vec()).to_vec();
        for id in ids.iter() {
            ecs.remove(*id);
        }
    }
}

clear() for the entire World doesn't help as well.
Note that call to len() method of the World returns correct number of entities (in the example above at the end of each loop iteration it will show 0), which means that removals were successful.
Was tested both on debug and release.
Legion version: 0.4.0
OS: Windows 10

Rua commented

This is typical for Rust's built-in types too. Vec will keep its allocation after you remove or clear. It only reduces the allocation if you call shrink_to or shrink_to_fit. Something like that could be added to World as well, which the user could then call periodically.

This is typical for Rust's built-in types too. Vec will keep its allocation after you remove or clear. It only reduces the allocation if you call shrink_to or shrink_to_fit. Something like that could be added to World as well, which the user could then call periodically.

If I remove items from Vec and add the same amount of items later, previously allocated memory will be reused and memory consumption will not grow - it will be constant for the same amount of items, but in case with removing and adding entities seems like memory is not reused and it's consumption is only growing with each add/remove iteration.