Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best choice for non-resizable dynamic length arrays in Rust?

I'm re-implementing a hashtable in Rust. Eventually I'd like to make this distributed and have quorums, but for now it's a hashtable on a single system.

I want the size of the table to be passed in as an argument so the table should be dynamically sized. I don't want the table to grow because that will mess with my hash function which works off a modulo operation. I see a couple of options:

  1. Arrays - cannot be dynamically sized
  2. Vectors - can grow
  3. Slices - can be dynamically sized & can't grow, but are just views onto Vecs and arrays, so I'll need a Vec/array anyways?

In C++, I could have just used a dynamically sized array. What's the best choice here?

like image 824
etk1220 Avatar asked Dec 19 '22 05:12

etk1220


1 Answers

A boxed slice is dynamically sized, the length cannot be changed once created, and it owns the contained data:

let the_vec: Vec<i32> = vec![1, 2, 3];
let the_boxed_slice: Box<[i32]> = the_vec.into_boxed_slice();

The types aren't required here, they are just present for pedagogical reasons.


However, it's dubious whether you will get any performance benefit. A Vec is three pointer sized values (data, size, capacity). A Box<[T]> is only two: data and size. The overhead of having the extra value is minuscule in most cases.

The main benefit is to be statically guaranteed that the size won't change; you won't statically know that it's a certain size. Such a guarantee might happen if type-level numbers ever happen.

See also:

  • Performance comparison of a Vec and a boxed slice
like image 184
Shepmaster Avatar answered May 23 '23 17:05

Shepmaster