我想在回傳之前修改一個集合:
fn main() {
println!("{:?}", compute()); // should print [[2, 1, 0], [5, 4, 3]]
}
// u8 is just a placeholder, so impl Copy is considered cheating :)
fn compute() -> Vec<Vec<u8>> {
let a = vec![0, 1, 2];
let b = vec![3, 4, 5];
let mut result = Vec::new();
result.push(a);
result.push(b);
// avoids allocations from:
//
// result.iter()
// .map(|r| {
// r.reverse()
// r
// })
// .collect::<Vec<_>>()
result.into_iter().for_each(|mut r| r.reverse());
// errors out: the collection was consumed the line above
result
}
一個集合已經被分配了Vec::new(),所以在這里分配第二個集合似乎是一種浪費。我假設那是什么.collect()。
- 如何避免超額分配?
- 有什么簡單的方法可以知道發生了多少分配?在 golang 中它和 . 一樣簡單
go test -bench=.,但在 Rust 中我找不到任何類似的東西。
鏈接到游樂場
uj5u.com熱心網友回復:
您需要對&mut每個內部向量使用 a,因為您可以只使用iter_mutwhich uses&mut Self而不是Self外部向量。
// u8 is just a placeholder, so impl Copy is considered cheating :)
fn compute() -> Vec<Vec<u8>> {
let a = vec![0, 1, 2];
let b = vec![3, 4, 5];
let mut result = Vec::new();
result.push(a);
result.push(b);
result.iter_mut().for_each(|r| r.reverse());
result
}
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432697.html
上一篇:為什么numpy.view(bool)使numpy.logical_and明顯更快?
下一篇:有效填充2DSciPy稀疏矩陣
