Elixir 的 defstruct 的性能优势是什么?

What are the performance advantage of Elixir's defstruct?

我对 Elixir 结构的理解是这样的;
1. 它不能保存编译时定义的键以外的键。
2.它可以有默认值,在编译时评估。

有什么性能优势吗?
另外,有什么我遗漏的吗?

好吧,Elixir 是开源的。从实施中可能很容易看出 Kernel.defstruct/1, everything it does is it defines __struct__ method on the module where it was called (only the false part 可以考虑不失一般性的情况。

其他一切都负责通知 Elixir 编译器有关此结构的信息,以便为其启用新语法 (%MyStruct{}) 并将有关该结构的一些元信息存储到编译器全局变量中。

结构下面由 bare map %{} 表示,没有任何性能提升空间。

struct 的主要优势不在于性能,而在于代码的可读性和正确性。考虑像 %{id: 123} 这样的东西——我们不知道那张地图代表什么。使用结构我们可以有 %Person{id: 123}%Company{id: 123},它们是不同的东西。此外,正如 GavinBrelstaff 所提到的,人们可以通过模式匹配轻松地表达出预期的结果。结构中旨在正确性的另一个示例是 @enforce_keys - 通过在您的结构中设置它,您可以确保它的任何正常创建的实例都将具有给定的键。