Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the JIT Compiler treat value types?

Tags:

c#

jit

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?

like image 934
amitabha Avatar asked Nov 13 '22 03:11

amitabha


1 Answers

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.

like image 62
Jon Skeet Avatar answered Nov 15 '22 00:11

Jon Skeet