O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Inspecting memory usage with std::mem

If you're interested in how much all these various collector types use memory, you don't have to guess. The std::mem module contains useful functions for checking that at runtime. Let's take a look at a couple:

  • size_of returns the size of a type given via a generic type
  • size_of_val returns the size of a value given as a reference

In case we were skeptical about the zero-cost claims of some of the preceding generic types, we can use these functions to check the overhead. The call style for size_of may be a bit peculiar if you're not familiar with it yet: we are not actually giving it anything as a parameter; we're just explicitly calling it against a type. Let's take a look at some sizes:

 // mem-introspection.rs ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required