在某天移动对象时,Rust可以优化掉按位复制吗? [英] Can Rust optimise away the bit-wise copy during move of an object someday?

查看:124
本文介绍了在某天移动对象时,Rust可以优化掉按位复制吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑代码段

struct Foo {
    dummy: [u8; 65536],
}

fn bar(foo: Foo) {
    println!("{:p}", &foo)
}

fn main() {
    let o = Foo { dummy: [42u8; 65536] };
    println!("{:p}", &o);
    bar(o);
}

该程序的典型结果

0x7fffc1239890
0x7fffc1229890

地址不同.

显然,已复制大数组dummy,如编译器的move实现中所预期的那样.不幸的是,这可能对性能产生不小的影响,因为dummy是一个非常大的数组.这种影响会迫使人们选择通过引用来代替传递参数,即使该函数实际上在概念上消耗"了参数.

Apparently, the large array dummy has been copied, as expected in the compiler's move implementation. Unfortunately, this can have non-trivial performance impact, as dummy is a very large array. This impact can force people to choose passing argument by reference instead, even when the function actually "consumes" the argument conceptually.

由于Foo不派生Copy,因此对象o被移动.由于Rust禁止访问已移动的对象,是什么阻止了bar重用"原始对象o,从而迫使编译器生成潜在的昂贵逐位副本?有基本的困难吗?还是有一天我们会看到编译器优化掉按位复制吗?

Since Foo does not derive Copy, object o is moved. Since Rust forbids the access of moved object, what is preventing bar to "reuse" the original object o, forcing the compiler to generate a potentially expensive bit-wise copy? Is there a fundamental difficulty, or will we see the compiler someday optimise away this bit-wise copy?

推荐答案

鉴于在Rust中(与C或C ++不同),值的地址不重要,在语言方面没有任何意义可以防止副本被删除.

Given that in Rust (unlike C or C++) the address of a value is not considered to matter, there is nothing in terms of language that prevents the elision of the copy.

但是,今天rustc并没有优化任何东西:所有优化都委托给LLVM,看来您在这里遇到了LLVM优化器的局限性(尚不清楚此限制是由于LLVM接近C的语义还是仅仅是因为的遗漏).

However, today rustc does not optimize anything: all optimizations are delegated to LLVM, and it seems you have hit a limitation of the LLVM optimizer here (it's unclear whether this limitation is due to LLVM being close to C's semantics or is just an omission).

因此,有两种途径可以改善代码生成:

So, there are two avenues of improving code generation for this:

  • 教LLVM执行此优化(如果可能)
  • 教rustc来执行此优化(由于具有MIR,优化过程已进入rustc)

但是现在您可能只是想避免在堆栈上分配如此大的对象,例如,可以Box.

but for now you might simply want to avoid such large objects from being allocated on the stack, you can Box it for example.

这篇关于在某天移动对象时,Rust可以优化掉按位复制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆