Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the runtime memory size of an object?

Tags:

memory

rust

I am trying to figure out how to get the size in bytes of an object in Rust where the size may or may not be known at compile time. I would like to be able to fetch the number of bytes at any point during the runtime of the program. Here's an example.

let mut v: Vec<SomeStruct> = Vec::new();

loop {

    v.push(get_some_struct());

    print_consumed_memory_of_vec(&v);
}

I would like to have a more generic way this than doing mem::size_of<SomeStruct> * v.len() because often you have a trait or something where the size is not known at compile time.

like image 602
DataDao Avatar asked Jun 27 '20 17:06

DataDao


1 Answers

Use std::mem::size_of_val to get the size of a slice:

println!("The useful size of `v` is {}", size_of_val(&*v));

Note:

  • You must dereference a Vec<T> to get a &[T] because the size of the Vec itself is just the size of three pointers, but you actually want the size of the slice that the data pointer refers to. This isn't a problem when you already have a &[T] or a &dyn Trait, or generally any &U where U is the thing whose size you want to know.
  • This gives you the size of the populated part of the Vec; that is, the same thing as size_of::<T>() * v.len(). If v has unused capacity, that will not be reflected by size_of_val(&*v). There is no general method that tells you the size of an allocation; you must calculate that yourself. This also makes a difference for, for instance, Rc<T> instead of Vec<T> -- the Rc stores its reference counts in the same allocation with the T, but they will not be counted if you write size_of_val(&*rc).
like image 99
trent Avatar answered Sep 24 '22 00:09

trent