I am reading C# in depth by Jon Skeet. Quoting from the third chapter:
The JIT can treat value types in a particularly clever way that manages to eliminate boxing and unboxing in many situations. In some cases, this can make a huge difference to performance in terms of both speed and memory consumption.
Could someone please explain what this means exactly, preferably with an example?
Let's take List<int> as an example. That is backed by a genuine int[], and the JIT will JIT-compile the code specifically for the int type argument, so that any code using a T within List<T> should get any optimizations as if the code had been written just for integers.
Compare this with Java's generics, where the only valid type arguments are class types - so even though it's valid to write:
// Java code!
List<Integer> integers = new ArrayList<Integer>();
integers.add(10);
int x = integers.get(0); // x = 10
That performs a boxing and unboxing operation in the background. The equivalent C# code would involve no boxing at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With