变体中没有数据的枚举的 bincode 序列化是否与引用静态值一样优化?

Is bincode serialization of an enum with no data in the variants as optimized as referencing a static value?

我有时这样使用serde and bincode

use serde::{Deserialize, Serialize};
use bincode;

#[derive(Serialize, Deserialize)]
pub enum PlainDryEnum {
    FirstVariant,
    Second,
    Third,
}

fn example() {
    let message = bincode::serialize(&PlainDryEnum::Second)
        .expect("Could not serialize variant.");
}

每当我序列化这些变体之一时,我想

hey.. the actual content of message is statically known, maybe I should make it const or at least lazy_static, so I would not rely on a useless dynamic call to serialize.

那我觉得

well.. I guess I could also do the same for every variant in PlainDryEnum. Try it with a macro.

最后我觉得

wait a minute.. is this not a job for the compiler?

我应该担心这种程度的优化吗?在这种情况下,编译器是否优化了对 serialize 的调用,并只是(在精神上)用常量替换此代码?

let message = &1;

bincode::serialize is not const fn所以不能保证在编译时执行。这意味着不能保证编译器会替换调用。