文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Static Constructor(Type Constructor)

Static Constructor(Type Constructor)

时间:2010-08-21  来源:RamondLee

there are two ways can make the Static Constructor be called.

1.  if you want to initialize a instance of this type

2.  if you want to access a static noninherited member of this type

 

please pay attention on the second one.  Before this moment, I thought the static constructor would be called whenever you write code about this type. But it is not like that.

The following code demonstrate what I mean:

  代码

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Child.Value);
            Console.ReadKey();
        }
    }

 public class Base
    {
        public static int Value { get; set; }
    }

    public class Child:Base
    {
        static Child()
        {
            Console.WriteLine("type constructor");
        }
    }

 

 

 the child's static constructor won't be called.

 

there are more details on book << CLR via C#>>  charpter 8  Part 3.

And there is a program shows you how JIT treat different kinds of type constructors. 

I changed the  main method in this program to verify a truth about JIT compiler: the IL code only JIT-compiled once. 

代码 public static void Main()
    {
        const Int32 iterations = 1000 * 1000 * 1000;
        Console.WriteLine("type in 'ok'  to continue:");
        string a = Console.ReadLine();
        while (a.Equals("ok"))
        {
            Console.WriteLine("type in 'ok' to excute the first method? ");
            a = Console.ReadLine();

            if (a.Equals("ok"))
                PerfTest1(iterations);

            PerfTest2(iterations);

            Console.WriteLine("type in 'ok'  to continue:");
            a = Console.ReadLine();

        }
        Console.ReadKey();
    }

 

 

 

if you replace the main method with this one, here is one possible output  that you can get :

 

the key about this problem is the JIT will emit the different code based on the execute of  type's  static constructor, the perfTest1 and perfTest2 are actually have the same content, the only different here is that they did not get JIT-compiled at the same time. whichever method you execute first will make the second method run faster.  you can see the output from PerfTest2 are always same(almost same),  how many times the method had been called. Because the PerfTest2 method are the first method got called here, that make it run very solw just like the first time for ever.

What does that mean? It means that the native code will be cached after its first generated, there won't have any optimization for these codes in the future. 

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载