jaemk / cached

Rust cache structures and easy function memoization
MIT License
1.58k stars 95 forks source link

Free memory when clear #24

Closed yagince closed 5 years ago

yagince commented 5 years ago

UnboundCache is not limited in size, so we want to release the memory when clearing after a large amount of caching. so I changed it to initialize the old cache memory by initializing with HashMap::new. HashMap::clear is keeps the allocated memory.

https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.clear

Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.

What do you think?

I tested it with the following code.

    #[test]
    fn clear_heavy_cache() {
        let mut c = UnboundCache::new();

        for i in 0..5_000_000 {
            if i % 1_000_000 == 0 {
                println!("{}", i);
            }
            c.cache_set(format!("Key: {}", i), format!("Value: {}", i));
        }

        println!("before clear");

        c.cache_clear();

        println!("after clear");

        std::thread::sleep(std::time::Duration::from_secs(15));

        println!("done");

    }

before

before

after

after

jaemk commented 5 years ago

Thanks!