I’m trying to understand which of two solutions are preferred from a performance perspective.
For example, I have two pieces of code:
1) Boxing / Unboxing
int val = 5;
Session["key"] = val;
int val2 = (int)Session["key"];
2) Casting (IntObj has int Value property to store int)
IntObj val = new IntObj(5);
Session["key"] = val;
int val2 = ((IntObj )Session["key"]).Value;
What is the memory management difference between these examples?
Is there a faster way to perform such operations?
NOTE: Session is just for example, it can be any Dictionary<string, object>
It looks like what you are really doing here is comparing manual boxing with inbuilt boxing. The inbuilt boxing has been highly optimised – so I wouldn’t expect to see a huge difference here, but we can check. Importantly, note that both have the same memory impact: one heap object containing one
intfield, perintboxed/wrapped.The following shows pretty-much identical times for the two approached; I would say, therefore, just box it the direct / inbuilt way.
Note: run it in release mode, without a debugger (ideally at the command line). Note the first call is there to pre-JIT everything.