I need to create a known number of dynamically growing vectors of integers. The number of the vectors are known (N = 10^7) as well as the maximum size of any of those vectors (M = 2*10^5).
My naive idea was:
let list: Vec<Vec<i32>> = vec![Vec::new(); N];
This works but takes ~3s on an i7 2.8 GHz. I've looked into arrays, which generally have 2x performance over vectors:
// Does not compile!
let list: [Vec<i32>; N] = [Vec::new(); N];
This does not compile as Vec
is not copyable. I wasn't able to wrap Vec
with a struct and implement Copy
on it.
I could use an array of arrays ([[i32; M]; N]
) but this would allocate way too much memory.
How can I create a list of dynamically sized arrays that performs well?
For comparison, the same in C++ performs under a second:
std::vector<std::vector<int32_t>> list(N, std::vector<int32_t>());
I was thinking of using a linked list instead of vectors, but I feel there is an elegant solution for this problem.
Update: as @Shepmaster pointed out correctly, compiling with --release
should be the base of comparison. This way cargo build --release
provides ~45x speed increase, being twice as fast as clang with -O3
.