我可以在Rust中按值有效地返回对象吗? [英] Can I efficiently return an object by value in Rust?
问题描述
我想用一个函数初始化一个大对象.目前,我有:
I would like to initialize a large object with a function. Currently I have:
fn initialize(mydata: &mut Vec<Vec<MyStruct>>) { /* ... */ }
我希望拥有:
fn initialize() -> Vec<Vec<MyStruct>> { /* ... */ }
我听说C ++通常会实现返回值优化(RVO),如果您幸运的话,并且具有良好的编译器.我们可以在此处禁用复制,并通过传递给函数的隐藏指针将其返回吗? RVO是语言的一部分还是可选的优化?
I've heard that C++ often implements return value optimization (RVO), if you are lucky and have a good compiler. Can we disable copying here and have it returned by a hidden pointer that is passed into the function? Is RVO part of the language or an optional optimization?
推荐答案
是的,您一定要写
fn initialize() -> Vec<Vec<MyStruct>> { ... }
(顺便说一句,Vec
并没有那么大-它只有3个指针大小的整数)
(By the way, a Vec
is not that large - it's only 3 pointer-sized integers)
Rust具有RVO,并且此在指南中刊登广告.您可以使用以下代码自己看到它:
Rust has RVO, and this is advertised in guides. You can see it yourself with this code:
#[inline(never)]
fn initialize() -> Vec<i32> {
Vec::new()
}
fn main() {
let v = initialize();
}
如果您以发布模式,输出程序集,您将看到以下内容:
If you compile this program in release mode on the playground, outputting assembly, among everything else you will see this:
playground::initialize:
movq $4, (%rdi)
xorps %xmm0, %xmm0
movups %xmm0, 8(%rdi)
retq
内联了
Vec::new()
,但是您可以看到一个想法-新鲜的Vec
实例的地址传递到%rdi
中的函数中,并且该函数将Vec
字段直接存储到此内存中,避免了不必要的操作通过堆栈复制.这就是它的称呼方式:
Vec::new()
was inlined, but you can see the idea - the address for the fresh Vec
instance is passed into the function in %rdi
, and the function stores Vec
fields directly into this memory, avoiding unnecessary copying through the stack. This is how it is called:
playground::main:
subq $24, %rsp
movq %rsp, %rdi
callq playground::initialize
您可以看到最终Vec
实例将直接放入堆栈存储器中.
You can see that eventually the Vec
instance will be put directly into the stack memory.
这篇关于我可以在Rust中按值有效地返回对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!