C
C#2y ago
joki

❔ 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
joki
jokiOP2y ago
or does that not matter because they are already allocated on the heap? since theyre in an array
Sossenbinder
Sossenbinder2y ago
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
joki
jokiOP2y ago
well not most likely, it will end up on the heap, [] is a reference type those create pointers to unmanaged memory
Sossenbinder
Sossenbinder2y ago
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
Anton
Anton2y ago
it should be optimized out for structs as that check is always true for structs
joki
jokiOP2y ago
false you mean?
cap5lut
cap5lut2y ago
shouldnt if (item == default) avoid boxing? u cant avoid boxing if ya check for null
Aaron
Aaron2y ago
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
Anton
Anton2y ago
yeah of course
Aaron
Aaron2y ago
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
Sossenbinder
Sossenbinder2y ago
Oh, TIL, that is very good to know It makes sense, but I had no idea that this will outright be skipped
MODiX
MODiX2y ago
Windows10CE#8553
sharplab.io (click here)
public class C {
[JitGeneric(typeof(int))]
public static void M<T>(T t) {
if ((object)t == null) Console.WriteLine("a");
}
}
public class C {
[JitGeneric(typeof(int))]
public static void M<T>(T t) {
if ((object)t == null) Console.WriteLine("a");
}
}
React with ❌ to remove this embed.
Aaron
Aaron2y ago
you can see the assembly doesn't have the WriteLine
Sossenbinder
Sossenbinder2y ago
Indeed
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server