In this section, we’ll see how to effectively use .Net Types in order to increase the application performance. As we all know that .Net Type system offers 2 kinds of type, 1) Reference Type and 2) Value Types. Reference types are nothing but i can say any class you are writing is a reference type getting allocated on the Heap. so, basically on reference types we can apply OOP methodology, locking and bunch of other methods.
However, in Value types you can’t get these flexibilities. Also, value types are getting allocated on stack avoiding pressure on Garbage collector. you should choose value types wisely means only choose value types when your application is performance critical otherwise Value types may include variety of complexities later in the program. consider a simple example shown below.
below program is fairly simple, 1st i allocated 10 million instances of int on the stack and then tried to reach out the last element in the list. I also repeated the same step 25 times and then at that time i captured the GC instances and time elapsed. Normally, we write simple program this way
Now, when i run the same, it will produce me the below result as shown below in the screen shot.
Now, in the 2nd version, what i am going to do is override the equals operation, so it does suppress the use of reflection at runtime, but still involves one boxing operation for comparison.
now, when i invoke the same like shown below.
then, it will produce me the below result. It does improve the performance.
Now, lets see the another example with IEquatable implementation.
it will produce me the optimized result.
so, contains method check for equality in the list and if we have collection like the above one, then it would be a big performance issue. Now, with IEquatble implementation same job is achieved and achieved faster. This interface has just one method and that is equals method and it takes value type as parameter. so, rather than relying on default implementation of object.valueType, this kind of approach will be really performance booster. Thanks for joining me.