When should I use a struct instead of a class?

后端 未结 15 2151
臣服心动
臣服心动 2020-11-22 13:00

MSDN says that you should use structs when you need lightweight objects. Are there any other scenarios when a struct is preferable over a class?

Some people might ha

15条回答
  •  太阳男子
    2020-11-22 13:16

    It is an old topic, but wanted to provide a simple benchmark test.

    I have created two .cs files:

    public class TestClass
    {
        public long ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    and

    public struct TestStruct
    {
        public long ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    Run benchmark:

    • Create 1 TestClass
    • Create 1 TestStruct
    • Create 100 TestClass
    • Create 100 TestStruct
    • Create 10000 TestClass
    • Create 10000 TestStruct

    Results:

    BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18362
    Intel Core i5-8250U CPU 1.60GHz (Kaby Lake R), 1 CPU, 8 logical and 4 physical cores
    .NET Core SDK=3.1.101
    [Host]     : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT  [AttachedDebugger]
    DefaultJob : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
    
    
    |         Method |           Mean |         Error |        StdDev |     Ratio | RatioSD | Rank |    Gen 0 | Gen 1 | Gen 2 | Allocated |
    |--------------- |---------------:|--------------:|--------------:|----------:|--------:|-----:|---------:|------:|------:|----------:|
    
    |      UseStruct |      0.0000 ns |     0.0000 ns |     0.0000 ns |     0.000 |    0.00 |    1 |        - |     - |     - |         - |
    |       UseClass |      8.1425 ns |     0.1873 ns |     0.1839 ns |     1.000 |    0.00 |    2 |   0.0127 |     - |     - |      40 B |
    |   Use100Struct |     36.9359 ns |     0.4026 ns |     0.3569 ns |     4.548 |    0.12 |    3 |        - |     - |     - |         - |
    |    Use100Class |    759.3495 ns |    14.8029 ns |    17.0471 ns |    93.144 |    3.24 |    4 |   1.2751 |     - |     - |    4000 B |
    | Use10000Struct |  3,002.1976 ns |    25.4853 ns |    22.5920 ns |   369.664 |    8.91 |    5 |        - |     - |     - |         - |
    |  Use10000Class | 76,529.2751 ns | 1,570.9425 ns | 2,667.5795 ns | 9,440.182 |  346.76 |    6 | 127.4414 |     - |     - |  400000 B |
    

提交回复
热议问题