2
    struct ValueTypeObject
    {
        private int x;
    }

    class RefTypeObject
    {
        private int x;
    }

    void main()
    {
        var a = new Dictionary<int, ValueTypeObject>();
        var b = new Dictionary<int, RefTypeObject>();
    }

Is there any benefit in using a over b?

For example, will ValueTypeObject in "a" get boxed/unboxed automatically or is there no boxing?

SpaceMonkey
  • 4,143
  • 5
  • 38
  • 60
  • A is definitely beneficial if the type of the value is **already** a `struct` (e.g. `int`). Other than that, this feels like a XY Problem - https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem . **Why** are you asking? – mjwills Sep 07 '19 at 13:29
  • The short answer is generally `No` though. But, like all things, you need to profile it to be sure. – mjwills Sep 07 '19 at 13:33
  • Depends on the size of the struct. General guidelines apply here too: [Choosing Between Class and Struct](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct) – Theodor Zoulias Sep 07 '19 at 13:45
  • in my opinion depends on how much your dictionary is big.difference will be shown in big data.in small data no difference . – A Farmanbar Sep 07 '19 at 13:56
  • 3
    Generic types [do not cause boxing](https://stackoverflow.com/q/4403055/11683), specifically because they are generic. The important difference here is not boxing, but the fact that `dict[index].x = 42` works in one way with classes and in [completely another](https://stackoverflow.com/q/1747654/11683) with structs. – GSerg Sep 07 '19 at 14:54
  • Not enough information. The use-case is too artificial. – H H Sep 07 '19 at 15:01
  • 2
    Value types are supported in .NET to make code more efficient. That is the case here as well, accessing a dictionary element of a value requires at least one memory read, accessing an object requires at least two. The overhead caused by the extra read is small, not easy to see back because of the overhead of the dictionary, which is highly variable. No boxing, Dictionary is generic. – Hans Passant Sep 07 '19 at 15:20
  • @HansPassant Thank you! that answers my question. – SpaceMonkey Sep 07 '19 at 16:28
  • 1
    It is key you do profiling here. @HansPassant is right - there is no boxing. But if the `struct` is large enough then the overhead of copying it around (which is an issue for `struct` but not `class`) can become an issue, as Theodor mentioned. https://ericlippert.com/2012/12/17/performance-rant/ – mjwills Sep 07 '19 at 23:02

0 Answers0