Rust 的 Option 类型的开销是多少? [英] What is the overhead of Rust's Option type?

查看:16
本文介绍了Rust 的 Option 类型的开销是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rust 中,引用永远不能为空,所以如果你真的需要空值,比如链表,你可以使用 Option 类型:

In Rust, references can never be null, so in case where you actually need null, such as a linked list, you use the Option type:

struct Element {
    value: i32,
    next: Option<Box<Element>>,
}

与简单的指针相比,这在内存分配和取消引用步骤方面涉及多少开销?编译器/运行时是否有一些魔法"可以使 Option 免费,或者比在非核心库中自己实现 Option 成本更低使用相同的 enum 构造,还是将指针包装在向量中?

How much overhead is involved in this in terms of memory allocation and steps to dereference compared to a simple pointer? Is there some "magic" in the compiler/runtime to make Option cost-free, or less costly than if one were to implement Option by oneself in a non-core library using the same enum construct, or by wrapping the pointer in a vector?

推荐答案

是的,有一些编译器魔法可以将 Option 优化为单个指针(大部分时间).>

Yes, there is some compiler magic that optimises Option<ptr> to a single pointer (most of the time).

use std::mem::size_of;

macro_rules! show_size {
    (header) => (
        println!("{:<22} {:>4}    {}", "Type", "T", "Option<T>");
    );
    ($t:ty) => (
        println!("{:<22} {:4} {:4}", stringify!($t), size_of::<$t>(), size_of::<Option<$t>>())
    )
}

fn main() {
    show_size!(header);
    show_size!(i32);
    show_size!(&i32);
    show_size!(Box<i32>);
    show_size!(&[i32]);
    show_size!(Vec<i32>);
    show_size!(Result<(), Box<i32>>);
}

打印以下大小(在 64 位机器上,因此指针为 8 个字节):

The following sizes are printed (on a 64-bit machine, so pointers are 8 bytes):

// As of Rust 1.22.1
Type                      T    Option<T>
i32                       4    8
&i32                      8    8
Box<i32>                  8    8
&[i32]                   16   16
Vec<i32>                 24   24
Result<(), Box<i32>>      8   16

注意&i32Box&[i32]Vec都在 Option!

这篇关于Rust 的 Option 类型的开销是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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