Rust 中的空指针优化是什么? [英] What is the null pointer optimization in Rust?

查看:59
本文介绍了Rust 中的空指针优化是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完全学习 Rust许多链表,作者提到:

In Learning Rust With Entirely Too Many Linked Lists, the author mentions:

但是,如果我们有一种特殊的枚举:

However, if we have a special kind of enum:

enum Foo {
    A,
    B(ContainsANonNullPtr),
}

空指针优化开始,消除了标签所需的空间.如果变体是 A,则整个枚举设置为所有 0.否则,变体是 B.这是有效的,因为 B 永远不可能都是 0 的,因为它包含一个非零指针.

the null pointer optimization kicks in, which eliminates the space needed for the tag. If the variant is A, the whole enum is set to all 0's. Otherwise, the variant is B. This works because B can never be all 0's, since it contains a non-zero pointer.

我猜作者是说(假设 A 是 4 位,B 是 4 位)

I guess that the author is saying that (assuming A is 4 bits, and B is 4 bits)

let test = Foo::A

内存布局是

0000 0000

但是

let test = Foo::B

内存布局是

some 8 bit non 0 value

这里到底优化了什么?不都是8位的,作者声称是什么意思

What exactly is optimized here? Aren't both representation always 8 bits What does it mean when the author claims

表示&&mutBoxRcArcVec 和 Rust 中的其他几个重要类型在放入 Option

It means &, &mut, Box, Rc, Arc, Vec, and several other important types in Rust have no overhead when put in an Option

推荐答案

空指针优化基本上意味着如果你有一个有两个变体的枚举,其中一个变体没有关联数据,而另一个变体有关联数据,其中全零的位模式不是有效值,那么枚举本身将占用与关联值完全相同的空间量,使用全零位模式来指示它是另一个变体.

The null pointer optimization basically means that if you have an enum with two variants, where one variant has no associated data, and the other variant has associated data where the bit pattern of all zeros isn't a valid value, then the enum itself will take exactly the same amount of space as that associated value, using the all zeroes bit pattern to indicate that it's the other variant.

换句话说,这意味着 Option<&T>&T 的大小完全相同,而不需要额外的单词.

In other words, this means that Option<&T> is exactly the same size as &T instead of requiring an extra word.

这篇关于Rust 中的空指针优化是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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