6

I am creating a lot of structs using Option<Vec<T>> instead of Vec<T> to not allocate memory when not needed. And I looked up this answer about the sizes of both Vec & Option<Vec>> and both were same.

So my question is this. Should I use Vec<T> and check its .len() for the same effect or continue using Option? Or are they equivalent?

Also originally I am a JavaScript Developer. And getting paranoid over to allocate or not to allocate.

pepsighan
  • 798
  • 9
  • 17
  • 1
    From a purely design standpoint, I believe it's *generally* more idiomatic to use `Option` for single items that may or may not exist (and which inherently don't have a "none" representation), and an empty collection for collections (since an empty collection itself implies "none"). Ex. [`as_bytes`](https://doc.rust-lang.org/std/string/struct.String.html#method.into_bytes), which returns an empty `Vec` if the `String` is empty, rather than a `None`. Especially in your case, with a struct - an `Option>` would need to be converted from `None` if items are added to the `Vec` later. – MutantOctopus Mar 19 '18 at 09:23
  • 2
    Instead of checking for `.len()` you should check `.is_empty()`. See the [`len_zero`-lint](https://rust-lang-nursery.github.io/rust-clippy/master/index.html#len_zero) – Tim Diekmann Mar 19 '18 at 12:01

1 Answers1

14

An empty Vec doesn't allocate, because there's nothing for it to store.

The two are the same size because of an optimisation the compiler uses, but this has no bearing on what the types mean. Even with this optimisation, an empty Vec and None aren't the same thing. One indicates the presence of an empty Vec, the other indicates the absence of any Vec at all. Depending on what exactly you're doing, the distinction could be important.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
DK.
  • 55,277
  • 5
  • 189
  • 162
  • That means a value should be stored in a type which represents its semantics? Which is my case leads to a simple `Vec`. Thanks. Also the reason I thought it allocated is because it stores pointers, len and such whereas None is a simple `null` which is nothing. – pepsighan Mar 19 '18 at 03:51
  • 2
    @csharad: It consumes space, yes, but it's the same amount of space that all `Vec`s consume, and it's not behind an allocation. – DK. Mar 19 '18 at 04:20