❔ Does this method cause boxing of value types?
I was looking through the list<T> class and noticed that the Contains<T>(T item) method attemps to cast the 'item' to an object - '(object) item', does this not cause boxing for value types?
15 Replies
or does that not matter because they are already allocated on the heap?
since theyre in an array
It will box a value type if you cast it to an object
Not sure about the array part, an array of value types will most likely end up on the heap, but things can become twisted
Technically there's stuff like stackalloc etc
So I wouldn't worry too much
If you really want to have non-boxing equality comparison, then I think EqualityComparer works
Since it's generic-based
well not most likely, it will end up on the heap, [] is a reference type
those create pointers to unmanaged memory
That's true, I mentioned likely since it is technically not written in stone, IIRC all of these details are only an implementation detail, so they could always swap out details
it should be optimized out for structs
as that check is always true for structs
false you mean?
shouldnt
if (item == default)
avoid boxing?
u cant avoid boxing if ya check for null
you don't want == default
this doesn't box
the entire branch is elided for value types
because a value type can never be null
it does not, the JIT is smart enough to know that a value type can never be null, and will get rid of the entire if
yeah of course
to clarify on why this is, this is a fast path specifically for checking for null reference types, so it can skip using EqualityComparer
a struct being the default doesn't really mean you can skip EqualityComparer
Oh, TIL, that is very good to know
It makes sense, but I had no idea that this will outright be skipped
you can see the assembly doesn't have the WriteLine
Indeed
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.