Why should a .NET struct be less than 16 bytes?

前端 未结 6 1383
独厮守ぢ
独厮守ぢ 2020-11-30 07:35

I\'ve read in a few places now that the maximum instance size for a struct should be 16 bytes.

But I cannot see where that number (16) comes from.

Browsing a

6条回答
  •  感情败类
    2020-11-30 07:50

    Here is a scenario where structs can exhibit superior performance:

    When you need to create 1000s of instances. In this case if you were to use a class, you would first need to allocate the array to hold the 1000s of instances and then in a loop allocate each instance. But instead if you were to use structs, then the 1000s of instances become available immediately after you allocate the array that is going to hold them.

    In addition, structs are extremely useful when you need to do interop or want to dip into unsafe code for performance reasons.

    As always there is a trade-off and one needs to analyze what they are doing to determine the best way to implement something.

    ps: This scenario came into play when I was working with LIDAR data where there could be millions of points representing x,y,z and other attributes for ground data. This data needed to be loaded into memory for some intensive computation to output all kinds of stuff.

提交回复
热议问题