× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

What is the memory layout of a vector of arrays?

Chris Morgan
Jul 15, 2015
<p>The contents of a <code>Vec&lt;T&gt;</code> is, regardless of <code>T</code>, a single heap allocation, of <code>self.capacity() * std::mem::size_of::&lt;T&gt;()</code> bytes. (<code>Vec</code> overallocates—that’s the whole point of <code>Vec&lt;T&gt;</code> instead of <code>Box&lt;[T]&gt;</code>—so it’s the capacity, not the length, that matter in this calculation.) The actual <code>Vec&lt;T&gt;</code> itself takes three words (<a href="https://play.rust-lang.org/?code=fn%20main()%20%7B%0A%20%20%20%20println!(%22%7B%7D%22%2C%20std%3A%3Amem%3A%3Asize_of%3A%3A%3CVec%3C%5Bf32%3B%205%5D%3E%3E())%3B%0A%7D&amp;version=stable">24 bytes</a> on a 64-bit machine).</p> <p><code>[f32; 5]</code> is just a chunk of memory containing five 32-bit floating-point numbers, with no indirection; this comes to twenty bytes (hence <a href="https://play.rust-lang.org/?code=fn%20main()%20%7B%0A%20%20%20%20println!(%22%7B%7D%22%2C%20std%3A%3Amem%3A%3Asize_of%3A%3A%3C%5Bf32%3B%205%5D%3E())%3B%0A%7D&amp;version=stable"><code>std::mem::size_of::&lt;[f32; 5]&gt;() == 20</code></a>).</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31374179/What%20is%20the%20memory%20layout%20of%20a%20vector%20of%20arrays?/31374259">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus