取切片有什么区别:
fn relu(xs: &mut [f64]) {
xs.iter_mut().for_each(|x| *x = x.max(0.0));
}
并引用一个数组
fn relu<const L: usize>(xs: &mut [f64; L]) {
xs.iter_mut().for_each(|x| *x = x.max(0.0));
}
作为参数?
是否有它的用途,或者一个比另一个更好?
最佳答案
嗯,一个slice更通用,因为可以使用的类型更多:
fn relu(xs: &mut [f64]) {
xs.iter_mut().for_each(|x| *x = x.max(0.0));
}
您可以通过 &mut Vec
、&mut []
或 &mut [_; 调用
(几乎所有你可以从中制作切片的东西,记住切片只是一些连续序列的 View ),因为这些类型可以用作切片。relu
N]
同时:
fn relu<const L: usize>(xs: &mut [f64; L]) {
xs.iter_mut().for_each(|x| *x = x.max(0.0));
}
只能在 [f64; L]
, and 为每个使用的 L
生成一个新函数,在这种情况下几乎是资源的损失 .
正如@Masklinn 评论的那样:
OTOH a reference to an array means the iteration size is definitely known at compile-time, which can allow optimisations which the slice version may not be able to work out. So sometimes using an array reference can make sense as an optimisation assistance (in this case relu would probably be a major candidate for inlining so the important bit would really be what the type is in the caller).
关于arrays - 使用切片和使用对数组的引用作为参数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71586633/