23th Day
Hey Guys, I hope that you are Enjoying with my blogs writing and in previous blog we have learnt about Memory Leak , Garbage Collector and Today's we will learn Boxing and Unboxing . Let's see
Boxing ,When a value type is move to a reference type its called Boxing and vice versa for Unboxing.
For Example In this code
int i = 10;//Value type
object o = i;//Boxing
int y=(int)o;//Unboxing
- Boxing is an implicit Conversion from value type to reference type.
- Here i=10 has stored in stack with address above shown in diagram its moving value i to o its a value type.
- Unboxing is an explicit Conversion from reference type to value type.
- And in heap o=10 its also moving from o to y its a reference type.
static void Main(string[] args)
{ //Line1 Warm period
Heavyloop();
Heavyloop();
//Line2
Stopwatch s1 = new Stopwatch();
s1.Start();
Heavyloop();
s1.Stop();
//Line3
Console.WriteLine(s1.ElapsedTicks);
Console.WriteLine("Hello World!");
Console.ReadLine();
}
- Line 1: Function will run as it is for warmup period and then actual measuring will start from Line 2.
- Line2: Stopwatch measure time below of milli sec and now will start measure its ElapsedTicks.static void Heavyloop(){for(int i=0; i<100000;i++){int z = 10;//Value Typeobject x = z;// reference type}}
- static void Heavyloop(), in this function we written code for boxing and Unboxing how much time it will take in performance. For that we set stopwatch.
- stopwatch, find function how much time taking for execution.
- Now let's run this code ,sometimes give 5 digits figure or 4 digits figure
- 1st output ElapsedTicks:
- 2nd output ElapsedTicks
- 3rd output ElapsedTicks
- It means that in non Primitive Data type, Due to Boxing and Unboxing its figure digits are different most of the time may be 4 to 5 digits.
- But in case of Primitive Data type always be the same figure due to no Boxing , Unboxing occurs.
- It is similar to array, it provides more flexible way to work with group of objects.
- It can grow and shrink Dynamically. // line 1int[] salesfigures = new int[] { 1000, 2000 };// line 2ArrayList l = new ArrayList();l.Add(1);l.Add("one");Console.WriteLine("Hiii"); /line 3List<int> Is = new List<int>();Is.Add(1);
- Line 1: It is Strongly typed and there are no Boxing/Unboxing so its performance will be faster. Its resizing is difficult. This is an Array.
- Line 2: Boxing/Unboxing will be happen that's why its performance will be slower but it will be very flexible. This is the array list.
- List<T>, Dictionary< Tkey, Tvalue>, sortedlist<Tkey,Tvalue>, Queue<T>, Stack<T>, Hashset<T> are used in Generic Collection.
- There are three types of Collection
- Array
- Array list
- Generic list.
Must watch this video for more detail learning...
Thank You...! for reading my Article...
No comments:
Post a Comment