Why does LayoutKind.Sequential work differently if a struct contains a DateTime field?

后端 未结 6 2363
名媛妹妹
名媛妹妹 2020-12-05 07:17

Why does LayoutKind.Sequential work differently if a struct contains a DateTime field?

Consider the following code (a console app which must be compiled with \"unsaf

6条回答
  •  悲哀的现实
    2020-12-05 07:51

    A few factors

    • doubles are a lot faster if they are aligned
    • CPU caches may work better if there are no “holes” in the struck

    So the C# compiler has a few undocumented rules it uses to try to get the “best” layout of structs, these rules may take into account the total size of a struct, and/or if it contains another struct etc. If you need to know the layout of a struct then you should specify it yourself rather than letting the compiler decide.

    However the LayoutKind.Sequential does stop the compiler changing the order of the fields.

提交回复
热议问题