我有一串生成数组并将它们返回到调用堆栈的函数.粗略地说,函数签名是:
fn solutions(...) -> [[u64; M]; N] { /* run iterator on lots of problem sets */ }
fn generate_solutions(...) -> impl Iterator<Item=[u64; M]> { /* call find_solution on different problem sets */ }
fn find_solution(...) -> [u64; M] { /* call validate_candidate with different candidates to find solution */ }
fn validate_candidate(...) -> Option<[u64; M]> {
let mut table = [0; M];
// do compute intensive work
if works { Some(table) } else { None }
}
我的理解是,Rust实际上不会在调用堆栈中向上copy个数组,而是优化复制.
但这不是我所看到的.当我切换到Vec
时,我看到速度提高了20倍,唯一的变化是[u64;M]
到Vec<u64>
.所以,它完全是一遍又一遍地复制array.
所以为什么是数组而不是Vec
,每个人都会问.嵌入式环境.no_std
.
如何鼓励Rust优化这些数组副本?