c#基础系列之值类型和引用类型的深入理解

2020-01-05 09:22:38丽君
  • 值类型的字段复制到新分配的堆内存中
  • 返回对象的地址,这个地址就是这个对象的引用

    拆箱发生了什么过程呢:

    • 获取已经装箱的值类型实例的指针
    • 把获取到的值复制到栈

      所以装箱是比较耗费性能的,还有可能引发一次GC操作,而拆箱只是一个获取指针的过程耗费资源要比装箱小的多。注意:一个对象拆箱之后只能还原为原先未装箱之前的类型,例如:你不能把int32类型装箱后还原为int16类型。 所以面试的时候可以和面试官装B一下了~~

      c#,值类型,引用类型

      测试例子

      值类型引用类型分别初始化N次消耗的时间,代码如下

      
      static void Main(string[] args)
       {
       Console.WriteLine("test start");
       int totalCount = 10000000;
       Stopwatch sw = new Stopwatch();
       sw.Start();
       for (int i = 0; i < totalCount; i++)
       {
        TestRef temp = new TestRef() { Id = i, Name = "test" };
       }
       sw.Stop();
       Console.WriteLine($"引用类型耗时:{sw.ElapsedMilliseconds}");
       sw.Reset();
       sw.Start();
      
       for (int i = 0; i < totalCount; i++)
       {
        TestVal temp = new TestVal() { Id = i, Name = "test" };
       }
       sw.Stop();
       Console.WriteLine($"值类型耗时:{sw.ElapsedMilliseconds}");
       Console.Read();
       }
      
       class TestRef
       {
       public int Id { get; set; }
       public string Name { get; set; }
       }
       struct TestVal
       {
       public int Id { get; set; }
       public string Name { get; set; }
       }