Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is allocating a struct on the heap or having a struct own a heap pointer more idiomatic?

Tags:

rust

I have a type that occupies too much space to be allocated on the stack:

struct Foo {
    lots_of_bytes: [u8; 1024 * 10],
    bar: bool,
    baz: isize,
}

There are two obvious solutions:

let foo = Box::new(Foo::new());

Or

struct Foo {
    lots_of_bytes: Box<[u8; 1024 * 10]>,
    bar: bool,
    baz: isize,
}

To summarize, I either allocate the entire struct on the heap, or I can have the struct own the heap pointer. Is either of these solutions considered the "idiomatic" solution? Or is it strictly subjective or dependent on context?

like image 965
w.brian Avatar asked Apr 12 '17 03:04

w.brian


People also ask

Are structs allocated on the heap?

Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.

Why is heap more preferred in working memory?

The best reason for heap allocation is that you cant always know how much space you need. You often only know this once the program is running. You might have an idea of limits but you would only want to use the exact amount of space required.


1 Answers

I think the question to ask yourself here is: will it ever make sense to place this struct in the stack? If the answer is no, you should probably enforce allocation on the heap. To achieve this, you have two alternatives:

  1. Use lots_of_bytes: Box<[u8; 1024 * 10]>.
  2. Use lots_of_bytes: [u8; 1024 * 10] and ensure that all constructors of Foo return Box<Foo (so it becomes impossible to create a Foo on the stack).

In my opinion, the first alternative is much better:

  • The struct definition of Foo shows clearly that the data must be stored on the heap.
  • This only requires boxing lots_of_bytes, instead of the whole struct. This means that bar and baz would be placed on the stack, so you have less indirection.

As for the second alternative, I can't think of any reason to prefer it and have never seen it in the wild.

like image 163
aochagavia Avatar answered Nov 13 '22 02:11

aochagavia