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 itconst
or at leastlazy_static
, so I would not rely on a useless dynamic call toserialize
.
然后我想
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
不是 const fn所以不能保证在编译时执行。这意味着不能保证编译器会替换调用。
关于enums - 变体中没有数据的枚举的二进制代码序列化是否与引用静态值一样优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60198198/