What's the difference between struct and class in .NET?

前端 未结 19 1402
一向
一向 2020-11-22 01:51

What\'s the difference between struct and class in .NET?

相关标签:
19条回答
  • 2020-11-22 02:09

    There is one interesting case of "class vs struct" puzzle - situation when you need to return several results from the method: choose which to use. If you know the ValueTuple story - you know that ValueTuple (struct) was added because it should be more effective then Tuple (class). But what does it mean in numbers? Two tests: one is struct/class that have 2 fields, other with struct/class that have 8 fields (with dimension more then 4 - class should become more effective then struct in terms processor ticks, but of course GC load also should be considered).

    P.S. Another benchmark for specific case 'sturct or class with collections' is there: https://stackoverflow.com/a/45276657/506147

    BenchmarkDotNet=v0.10.10, OS=Windows 10 Redstone 2 [1703, Creators Update] (10.0.15063.726)
    Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
    Frequency=3233540 Hz, Resolution=309.2586 ns, Timer=TSC
    .NET Core SDK=2.0.3
      [Host] : .NET Core 2.0.3 (Framework 4.6.25815.02), 64bit RyuJIT
      Clr    : .NET Framework 4.7 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2115.0
      Core   : .NET Core 2.0.3 (Framework 4.6.25815.02), 64bit RyuJIT
    
    
                Method |  Job | Runtime |     Mean |     Error |    StdDev |      Min |      Max |   Median | Rank |  Gen 0 | Allocated |
    ------------------ |----- |-------- |---------:|----------:|----------:|---------:|---------:|---------:|-----:|-------:|----------:|
      TestStructReturn |  Clr |     Clr | 17.57 ns | 0.1960 ns | 0.1834 ns | 17.25 ns | 17.89 ns | 17.55 ns |    4 | 0.0127 |      40 B |
       TestClassReturn |  Clr |     Clr | 21.93 ns | 0.4554 ns | 0.5244 ns | 21.17 ns | 23.26 ns | 21.86 ns |    5 | 0.0229 |      72 B |
     TestStructReturn8 |  Clr |     Clr | 38.99 ns | 0.8302 ns | 1.4097 ns | 37.36 ns | 42.35 ns | 38.50 ns |    8 | 0.0127 |      40 B |
      TestClassReturn8 |  Clr |     Clr | 23.69 ns | 0.5373 ns | 0.6987 ns | 22.70 ns | 25.24 ns | 23.37 ns |    6 | 0.0305 |      96 B |
      TestStructReturn | Core |    Core | 12.28 ns | 0.1882 ns | 0.1760 ns | 11.92 ns | 12.57 ns | 12.30 ns |    1 | 0.0127 |      40 B |
       TestClassReturn | Core |    Core | 15.33 ns | 0.4343 ns | 0.4063 ns | 14.83 ns | 16.44 ns | 15.31 ns |    2 | 0.0229 |      72 B |
     TestStructReturn8 | Core |    Core | 34.11 ns | 0.7089 ns | 1.4954 ns | 31.52 ns | 36.81 ns | 34.03 ns |    7 | 0.0127 |      40 B |
      TestClassReturn8 | Core |    Core | 17.04 ns | 0.2299 ns | 0.2150 ns | 16.68 ns | 17.41 ns | 16.98 ns |    3 | 0.0305 |      96 B |
    

    Code test:

    using System;
    using System.Text;
    using System.Collections.Generic;
    using BenchmarkDotNet.Attributes;
    using BenchmarkDotNet.Attributes.Columns;
    using BenchmarkDotNet.Attributes.Exporters;
    using BenchmarkDotNet.Attributes.Jobs;
    using DashboardCode.Routines.Json;
    
    namespace Benchmark
    {
        //[Config(typeof(MyManualConfig))]
        [RankColumn, MinColumn, MaxColumn, StdDevColumn, MedianColumn]
        [ClrJob, CoreJob]
        [HtmlExporter, MarkdownExporter]
        [MemoryDiagnoser]
        public class BenchmarkStructOrClass
        {
            static TestStruct testStruct = new TestStruct();
            static TestClass testClass = new TestClass();
            static TestStruct8 testStruct8 = new TestStruct8();
            static TestClass8 testClass8 = new TestClass8();
            [Benchmark]
            public void TestStructReturn()
            {
                testStruct.TestMethod();
            }
    
            [Benchmark]
            public void TestClassReturn()
            {
                testClass.TestMethod();
            }
    
    
            [Benchmark]
            public void TestStructReturn8()
            {
                testStruct8.TestMethod();
            }
    
            [Benchmark]
            public void TestClassReturn8()
            {
                testClass8.TestMethod();
            }
    
            public class TestStruct
            {
                public int Number = 5;
                public struct StructType<T>
                {
                    public T Instance;
                    public List<string> List;
                }
    
                public int TestMethod()
                {
                    var s = Method1(1);
                    return s.Instance;
                }
    
                private StructType<int> Method1(int i)
                {
                    return Method2(++i);
                }
    
                private StructType<int> Method2(int i)
                {
                    return Method3(++i);
                }
    
                private StructType<int> Method3(int i)
                {
                    return Method4(++i);
                }
    
                private StructType<int> Method4(int i)
                {
                    var x = new StructType<int>();
                    x.List = new List<string>();
                    x.Instance = ++i;
                    return x;
                }
            }
    
            public class TestClass
            {
                public int Number = 5;
                public class ClassType<T>
                {
                    public T Instance;
                    public List<string> List;
                }
    
                public int TestMethod()
                {
                    var s = Method1(1);
                    return s.Instance;
                }
    
                private ClassType<int> Method1(int i)
                {
                    return Method2(++i);
                }
    
                private ClassType<int> Method2(int i)
                {
                    return Method3(++i);
                }
    
                private ClassType<int> Method3(int i)
                {
                    return Method4(++i);
                }
    
                private ClassType<int> Method4(int i)
                {
                    var x = new ClassType<int>();
                    x.List = new List<string>();
                    x.Instance = ++i;
                    return x;
                }
            }
    
            public class TestStruct8
            {
                public int Number = 5;
                public struct StructType<T>
                {
                    public T Instance1;
                    public T Instance2;
                    public T Instance3;
                    public T Instance4;
                    public T Instance5;
                    public T Instance6;
                    public T Instance7;
                    public List<string> List;
                }
    
                public int TestMethod()
                {
                    var s = Method1(1);
                    return s.Instance1;
                }
    
                private StructType<int> Method1(int i)
                {
                    return Method2(++i);
                }
    
                private StructType<int> Method2(int i)
                {
                    return Method3(++i);
                }
    
                private StructType<int> Method3(int i)
                {
                    return Method4(++i);
                }
    
                private StructType<int> Method4(int i)
                {
                    var x = new StructType<int>();
                    x.List = new List<string>();
                    x.Instance1 = ++i;
                    return x;
                }
            }
    
            public class TestClass8
            {
                public int Number = 5;
                public class ClassType<T>
                {
                    public T Instance1;
                    public T Instance2;
                    public T Instance3;
                    public T Instance4;
                    public T Instance5;
                    public T Instance6;
                    public T Instance7;
                    public List<string> List;
                }
    
                public int TestMethod()
                {
                    var s = Method1(1);
                    return s.Instance1;
                }
    
                private ClassType<int> Method1(int i)
                {
                    return Method2(++i);
                }
    
                private ClassType<int> Method2(int i)
                {
                    return Method3(++i);
                }
    
                private ClassType<int> Method3(int i)
                {
                    return Method4(++i);
                }
    
                private ClassType<int> Method4(int i)
                {
                    var x = new ClassType<int>();
                    x.List = new List<string>();
                    x.Instance1 = ++i;
                    return x;
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:11

    As previously mentioned: Classes are reference type while Structs are value types with all the consequences.

    As a thumb of rule Framework Design Guidelines recommends using Structs instead of classes if:

    • It has an instance size under 16 bytes
    • It logically represents a single value, similar to primitive types (int, double, etc.)
    • It is immutable
    • It will not have to be boxed frequently
    0 讨论(0)
  • 2020-11-22 02:12

    Difference between Structs and Classes:

    • Structs are value type whereas Classes are reference type.
    • Structs are stored on the stack whereas Classes are stored on the heap.
    • Value types hold their value in memory where they are declared, but reference type holds a reference to an object memory.
    • Value types destroyed immediately after the scope is lost whereas reference type only the variable destroy after the scope is lost. The object is later destroyed by the garbage collector.
    • When you copy struct into another struct, a new copy of that struct gets created modified of one struct won't affect the value of the other struct.
    • When you copy a class into another class, it only copies the reference variable.
    • Both the reference variable point to the same object on the heap. Change to one variable will affect the other reference variable.
    • Structs can not have destructors, but classes can have destructors.
    • Structs can not have explicit parameterless constructors whereas classes can. Structs don't support inheritance, but classes do. Both support inheritance from an interface.
    • Structs are sealed type.
    0 讨论(0)
  • 2020-11-22 02:13

    From Microsoft's Choosing Between Class and Struct ...

    As a rule of thumb, the majority of types in a framework should be classes. There are, however, some situations in which the characteristics of a value type make it more appropriate to use structs.

    CONSIDER a struct instead of a class:

    • If instances of the type are small and commonly short-lived or are commonly embedded in other objects.

    X AVOID a struct unless the type has all of the following characteristics:

    • It logically represents a single value, similar to primitive types (int, double, etc.).
    • It has an instance size under 16 bytes.
    • It is immutable. (cannot be changed)
    • It will not have to be boxed frequently.
    0 讨论(0)
  • 2020-11-22 02:14

    Instances of classes are stored on the managed heap. All variables 'containing' an instance are simply a reference to the instance on the heap. Passing an object to a method results in a copy of the reference being passed, not the object itself.

    Structures (technically, value types) are stored wherever they are used, much like a primitive type. The contents may be copied by the runtime at any time and without invoking a customised copy-constructor. Passing a value type to a method involves copying the entire value, again without invoking any customisable code.

    The distinction is made better by the C++/CLI names: "ref class" is a class as described first, "value class" is a class as described second. The keywords "class" and "struct" as used by C# are simply something that must be learned.

    0 讨论(0)
  • 2020-11-22 02:14

    To add to the other answers, there is one fundamental difference that is worth noting, and that is how the data is stored within arrays as this can have a major effect on performance.

    • With a struct, the array contains the instance of the struct
    • With a class, the array contains a pointer to an instance of the class elsewhere in memory

    So an array of structs looks like this in memory

    [struct][struct][struct][struct][struct][struct][struct][struct]

    Whereas an array of classes looks like this

    [pointer][pointer][pointer][pointer][pointer][pointer][pointer][pointer]

    With an array of classes, the values you're interested in are not stored within the array, but elsewhere in memory.

    For a vast majority of applications this difference doesn't really matter, however, in high performance code this will affect locality of data within memory and have a large impact on the performance of the CPU cache. Using classes when you could/should have used structs will massively increase the number of cache misses on the CPU.

    The slowest thing a modern CPU does is not crunching numbers, it's fetching data from memory, and an L1 cache hit is many times faster than reading data from RAM.

    Here's some code you can test. On my machine, iterating through the class array takes ~3x longer than the struct array.

        private struct PerformanceStruct
        {
            public int i1;
            public int i2;
        }
    
        private class PerformanceClass
        {
            public int i1;
            public int i2;
        }
    
        private static void DoTest()
        {
            var structArray = new PerformanceStruct[100000000];
            var classArray = new PerformanceClass[structArray.Length];
    
            for (var i = 0; i < structArray.Length; i++)
            {
                structArray[i] = new PerformanceStruct();
                classArray[i] = new PerformanceClass();
            }
    
            long total = 0;
            var sw = new Stopwatch();
            sw.Start();
            for (var loops = 0; loops < 100; loops++)
            for (var i = 0; i < structArray.Length; i++)
            {
                total += structArray[i].i1 + structArray[i].i2;
            }
    
            sw.Stop();
            Console.WriteLine($"Struct Time: {sw.ElapsedMilliseconds}");
            sw = new Stopwatch();
            sw.Start();
            for (var loops = 0; loops < 100; loops++)
            for (var i = 0; i < classArray.Length; i++)
            {
                total += classArray[i].i1 + classArray[i].i2;
            }
    
            Console.WriteLine($"Class Time: {sw.ElapsedMilliseconds}");
        }
    
    0 讨论(0)
提交回复
热议问题