测试C# 类型转换效率问题

using System;
using System.Diagnostics;
 
namespace TestTypeChange
{
  public class MyClass{
      public int id = 0;
      public string name = "";
      public MyClass(int _id,string _name){
          id = _id;
          name = _name;
      }
  }
 
  class MainClass
  {
      public static void Main (string[] args)
      {
          Stopwatch stopwatch;
          object obj_ptr = null;
          MyClass myclass = new MyClass (0, "cjane");
          MyClass ref_myclass = null;
          int count = 100000000;
 
          stopwatch = Stopwatch.StartNew();
          for (int i = 0; i < count; i++)
              ref_myclass = myclass;
          stopwatch.Stop();
          Console.WriteLine("class to class: " + stopwatch.Elapsed);
 
          stopwatch = Stopwatch.StartNew();
          for (int i = 0; i < count; i++)
              obj_ptr = myclass;
          stopwatch.Stop();
          Console.WriteLine("class to object: " + stopwatch.Elapsed);
 
 
          stopwatch = Stopwatch.StartNew();
          for (int i = 0; i < count; i++)
              ref_myclass = (MyClass)obj_ptr;
          stopwatch.Stop();
          Console.WriteLine("object to class: " + stopwatch.Elapsed);
 
          int val = 100;
          int cp_val = 0;
 
          stopwatch = Stopwatch.StartNew();
          for (int i = 0; i < count; i++)
              ref_myclass = myclass;
          stopwatch.Stop();
          Console.WriteLine("value to value: " + stopwatch.Elapsed);
 
          stopwatch = Stopwatch.StartNew();
          for (int i = 0; i < count; i++)
              obj_ptr = val;
          stopwatch.Stop();
          Console.WriteLine("value to object: " + stopwatch.Elapsed);
 
 
          stopwatch = Stopwatch.StartNew();
          for (int i = 0; i < count; i++)
              cp_val = (int)obj_ptr;
          stopwatch.Stop();
          Console.WriteLine("object to value: " + stopwatch.Elapsed);
 
      }
  }
}
 
 
 
测试结果:
    class to class: 00:00:00.3463484
    class to object: 00:00:00.3520921
    object to class: 00:00:00.3760758
    value to value: 00:00:00.3303531
    value to object: 00:00:01.9317834
    object to value: 00:00:00.3482110    
 
 
测试得出C# 引用类型间的转换几乎和赋值时候差不多,性能损耗几乎忽略不计
但如果是整型值类型间的转换,把整型值类型转为object的时候,性能比较低
有兴趣的可以试试下字符串与object间的转换
 
 
 
 
 
 
posted @ 2017-03-26 21:06  游戏基  阅读(2030)  评论(0编辑  收藏  举报