Should the memory of an HashMap be freed when it goes out of scope?

Viewed 118

I thought the memory occupied by a rust HashMap was freed after the HashMap went out of scope, but in the following test it doesn't seem to happen.

use std::{collections::HashMap, thread, time::Duration};

fn func() {
    let mut map: HashMap<String, Vec<u8>> = HashMap::new();

    for i in 0..100_000 {
        map.insert(format!("{}", i), vec![0; 50_000]);
    }
}

fn main() {
    func();

    println!("LOOP");
    loop {
        thread::sleep(Duration::from_secs(5));
    }
}

Note: This program occupied about 5GB of RAM. When it arrives to the loop section the memory is still occupied.

enter image description here

Performing an analogue test with a vector:

use std::{thread, time::Duration};

fn func() {
    let mut x: Vec<Vec<u8>> = Vec::new();
    for _ in 0..100_000 {
        x.push(vec![0; 50_000])
    }
}
fn main() {
    func();
    println!("LOOP");

    loop {
        thread::sleep(Duration::from_secs(5));
    }
}

The result is very different, when it arrives to the loop the memory occupation drop to zero.

  • Rust version 1.60
  • Both the examples above are built on release mode

In this example (the index is an i32 instead a String) the memory is released to the os:

use std::{collections::HashMap, thread, time::Duration};

fn func() {
    let mut map: HashMap<i32, Vec<u8>> = HashMap::new();

    for i in 0..100_000 {
        map.insert(i, vec![0; 50_000]);
    }
}

fn main() {
    func();
    println!("LOOP");
    loop {
        thread::sleep(Duration::from_secs(5));
    }
}

UPDATE: Executing func in a thread seems to make the process release the memory.

0 Answers
Related