• 周六. 4月 27th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

beforefieldinit释义(3)

admin

11月 28, 2021

1.看下面的例子:

public static class MyClass<T>

{
    public static readonly DateTime Time = GetNow();
    private static DateTime GetNow()
    {
        Console.WriteLine("GetNow execute!");
        return DateTime.Now;
    }
}

class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("Main execute!");
        Console.WriteLine("int: " + MyClass<int>.Time);
        Thread.Sleep(3000);
        Console.WriteLine("string: " + MyClass<string>.Time);
        Console.ReadLine();
    }
}

结果如下:

GetNow execute!

GetNow execute!

Main execute!

int: 2009/9/8 15:34:31

string: 2009/9/8 15:34:31

看上面的结果在Main函数执行之前GetNow就执行了,就取到了DateTime.Now,所以输出的时间是一样的。

2.我们在上面的MyClass中加一个静态的构造函数我们在来看结果:

public static class MyClass<T>

{
    public static readonly DateTime Time = GetNow();
    private static DateTime GetNow()
    {

        Console.WriteLine("GetNow execute!");
        return DateTime.Now;
    }
    static MyClass() { }
}

结果如下:

Main execute!

GetNow execute!

int: 2009/9/8 15:40:12

GetNow execute!

string: 2009/9/8 15:40:15

我们可以发现每次的时间不同了。出现这种现象是由于当类没有静态构造函数的时候。在il中该类会被标记为BeforeFieldInit,这个是由编译器自动完成的。没有静态构造函数的时候初始化在刚进入方法的时候就发生了,而有静态函数的时候而且我们不需要做任何动作,只要有就可以,这个时候静态初始化在使用前才发生.我们可以通过看IL代码来证实这种现象,如下:

clip_image002

3.使用BeforeFieldInit会提高性能,下面我们就测试下,在测试我们需要计算代码执行时间,我们就是用老赵的组件,我稍稍做了一点修改,因为老赵用的win32 API是vista下的,为了以后查询方便,也贴下代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

using System.Threading;

using System.Runtime.InteropServices; 

namespace CSharpDemo

{
    public static class CodeTimer

    {

        public static void Initialize()

        {

            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            Time("", 1, () => { });

        } 

        public static void Time(string name, int iteration, Action action)

        {

            if (String.IsNullOrEmpty(name)) return;

            // 1.

            ConsoleColor currentForeColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Yellow;

            Console.WriteLine(name); 

            // 2.

            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

            int[] gcCounts = new int[GC.MaxGeneration + 1];

            for (int i = 0; i <= GC.MaxGeneration; i++)

            {
                gcCounts[i] = GC.CollectionCount(i);

            } 

            // 3.

            Stopwatch watch = new Stopwatch();

            watch.Start();

            long cycleCount = GetCycleCount();

            for (int i = 0; i < iteration; i++) action();

            long cpuCycles = GetCycleCount() - cycleCount;

            watch.Stop(); 

            // 4.

            Console.ForegroundColor = currentForeColor;

            Console.WriteLine("	Time Elapsed:	" + watch.ElapsedMilliseconds.ToString("N0") + "ms");

            Console.WriteLine("	CPU Cycles:	" + cpuCycles.ToString("N0")); 

            // 5.

            for (int i = 0; i <= GC.MaxGeneration; i++)

            {
                int count = GC.CollectionCount(i) - gcCounts[i];
                Console.WriteLine("	Gen " + i + ": 		" + count);
            } 

            Console.WriteLine();

        } 

        private static long GetCycleCount()

        {
            long l;

            long kernelTime, userTimer;

            GetThreadTimes(GetCurrentThread(), out l, out l, out kernelTime, out userTimer);

            return kernelTime + userTimer; 

        } 

        [DllImport("kernel32.dll", SetLastError = true)]

        static extern bool GetThreadTimes(IntPtr hThread, out long lpCreationTime,

           out long lpExitTime, out long lpKernelTime, out long lpUserTime); 

        [DllImport("kernel32.dll")]

        static extern IntPtr GetCurrentThread(); 

    }

}

View Code

下面我们开始测试,我们准备两个类:

public class MarkBeforeFieldInit

{

    public static string test;

} 

public class NoBeforeFieldInit

{
    public static string test;
    static NoBeforeFieldInit()

    {       

    }
}

测试代码如下:

class Program

{

    static void Main(string[] args)

    {
        CodeTimer.Initialize();
        int iteration = 1000 * 1000*1000; 

        CodeTimer.Time("MarkBeforeFieldInit", iteration, () => { MarkBeforeFieldInit.test = "test"; });

        CodeTimer.Time("NoBeforeFieldInit", iteration, () => { NoBeforeFieldInit.test= "test"; }); 

        CodeTimer.Time("MarkBeforeFieldInit2", iteration, () => { MarkBeforeFieldInit.test = "test"; });

        CodeTimer.Time("NoBeforeFieldInit2", iteration, () => { NoBeforeFieldInit.test = "test"; });     

    }
}

结果如下:

 

可以看出BeforeFieldInit方式的执行速度确实快,但为什么第二次执行的速度差不多呢?因为经过第一次执行后JIT编译器知道类型的构造器已经被调用了,所以第二次执行时不会显示对构造函数进行调用。

 

《beforefieldinit释义(3)》有4个想法
  1. PBN sites
    We will create a web of privately-owned blog network sites!

    Pros of our PBN network:

    We carry out everything SO THAT google DOES NOT understand that this is A self-owned blog network!!!

    1- We obtain web domains from separate registrars

    2- The main site is hosted on a VPS server (VPS is high-speed hosting)

    3- The rest of the sites are on separate hostings

    4- We assign a distinct Google profile to each site with confirmation in Google Search Console.

    5- We develop websites on WordPress, we don’t utilize plugins with the help of which malware penetrate and through which pages on your websites are created.

    6- We don’t reproduce templates and use only distinct text and pictures

    We do not work with website design; the client, if desired, can then edit the websites to suit his wishes

  2. Understanding COSC Certification and Its Importance in Horology
    COSC Accreditation and its Stringent Standards
    Controle Officiel Suisse des Chronometres, or the Official Swiss Chronometer Testing Agency, is the official Switzerland testing agency that verifies the precision and accuracy of timepieces. COSC accreditation is a mark of excellent craftsmanship and trustworthiness in chronometry. Not all timepiece brands follow COSC certification, such as Hublot, which instead sticks to its proprietary stringent standards with movements like the UNICO, attaining similar precision.

    The Art of Exact Chronometry
    The core system of a mechanized timepiece involves the mainspring, which delivers power as it unwinds. This system, however, can be prone to environmental factors that may affect its accuracy. COSC-validated mechanisms undergo rigorous testing—over fifteen days in various circumstances (five positions, 3 temperatures)—to ensure their durability and dependability. The tests measure:

    Average daily rate accuracy between -4 and +6 seconds.
    Mean variation, highest variation rates, and impacts of temperature changes.
    Why COSC Validation Is Important
    For timepiece aficionados and collectors, a COSC-certified watch isn’t just a piece of tech but a demonstration to enduring excellence and accuracy. It signifies a watch that:

    Presents excellent dependability and accuracy.
    Ensures assurance of quality across the entire design of the watch.
    Is probable to maintain its value better, making it a wise investment.
    Famous Timepiece Brands
    Several renowned manufacturers prioritize COSC certification for their watches, including Rolex, Omega, Breitling, and Longines, among others. Longines, for instance, presents collections like the Archive and Soul, which highlight COSC-validated mechanisms equipped with cutting-edge materials like silicon balance suspensions to improve durability and efficiency.

    Historic Context and the Evolution of Chronometers
    The idea of the chronometer dates back to the need for accurate chronometry for navigational at sea, emphasized by John Harrison’s work in the 18th cent. Since the official establishment of Controle Officiel Suisse des Chronometres in 1973, the certification has become a benchmark for assessing the accuracy of luxury watches, maintaining a legacy of superiority in watchmaking.

    Conclusion
    Owning a COSC-certified watch is more than an aesthetic selection; it’s a dedication to excellence and precision. For those valuing precision above all, the COSC validation offers peace of thoughts, ensuring that each accredited watch will perform reliably under various circumstances. Whether for personal contentment or as an investment, COSC-certified timepieces distinguish themselves in the world of horology, maintaining on a legacy of careful timekeeping.

  3. casibom
    Nihai Zamanın En Büyük Gözde Casino Platformu: Casibom

    Casino oyunlarını sevenlerin artık duymuş olduğu Casibom, en son dönemde adından çoğunlukla söz ettiren bir iddia ve casino sitesi haline geldi. Ülkemizdeki en başarılı kumarhane sitelerinden biri olarak tanınan Casibom’un haftalık bazda olarak değişen açılış adresi, sektörde oldukça yeni olmasına rağmen güvenilir ve kazandıran bir platform olarak ön plana çıkıyor.

    Casibom, rakiplerini geride bırakarak uzun soluklu bahis web sitelerinin üstünlük sağlamayı başarılı oluyor. Bu pazarda eski olmak önemlidir olsa da, katılımcılarla iletişimde bulunmak ve onlara ulaşmak da aynı miktar önemli. Bu noktada, Casibom’un gece gündüz yardım veren canlı destek ekibi ile rahatça iletişime ulaşılabilir olması büyük önem taşıyan bir fayda sunuyor.

    Hızla artan oyuncuların kitlesi ile ilgi çeken Casibom’un arka planında başarım faktörleri arasında, sadece casino ve gerçek zamanlı casino oyunları ile sınırlı olmayan kapsamlı bir hizmetler yelpazesi bulunuyor. Atletizm bahislerinde sunduğu geniş seçenekler ve yüksek oranlar, oyuncuları ilgisini çekmeyi başarmayı sürdürüyor.

    Ayrıca, hem spor bahisleri hem de casino oyunlar oyuncularına yönlendirilen sunulan yüksek yüzdeli avantajlı ödüller da dikkat çekiyor. Bu nedenle, Casibom hızla piyasada iyi bir tanıtım başarısı elde ediyor ve büyük bir oyuncuların kitlesi kazanıyor.

    Casibom’un kazanç sağlayan promosyonları ve ünlülüğü ile birlikte, siteye üyelik ne şekilde sağlanır sorusuna da değinmek elzemdir. Casibom’a mobil cihazlarınızdan, bilgisayarlarınızdan veya tabletlerinizden tarayıcı üzerinden kolaylıkla erişilebilir. Ayrıca, web sitesinin mobil cihazlarla uyumlu olması da büyük bir fayda getiriyor, çünkü artık pratikte herkesin bir cep telefonu var ve bu telefonlar üzerinden hızlıca erişim sağlanabiliyor.

    Mobil cep telefonlarınızla bile yolda canlı bahisler alabilir ve müsabakaları gerçek zamanlı olarak izleyebilirsiniz. Ayrıca, Casibom’un mobil cihazlarla uyumlu olması, ülkemizde casino ve oyun gibi yerlerin meşru olarak kapatılmasıyla birlikte bu tür platformlara erişimin büyük bir yolunu oluşturuyor.

    Casibom’un emin bir bahis platformu olması da önemli bir avantaj getiriyor. Belgeli bir platform olan Casibom, kesintisiz bir şekilde eğlence ve kar sağlama imkanı sunar.

    Casibom’a kullanıcı olmak da oldukça basittir. Herhangi bir belge koşulu olmadan ve bedel ödemeden siteye rahatça üye olabilirsiniz. Ayrıca, web sitesi üzerinde para yatırma ve çekme işlemleri için de çok sayıda farklı yöntem bulunmaktadır ve herhangi bir kesim ücreti talep edilmemektedir.

    Ancak, Casibom’un güncel giriş adresini takip etmek de elzemdir. Çünkü canlı iddia ve oyun platformlar popüler olduğu için hileli platformlar ve dolandırıcılar da belirmektedir. Bu nedenle, Casibom’un sosyal medya hesaplarını ve güncel giriş adresini düzenli aralıklarla kontrol etmek gereklidir.

    Sonuç, Casibom hem itimat edilir hem de kazanç sağlayan bir casino web sitesi olarak ilgi çekici. Yüksek bonusları, geniş oyun seçenekleri ve kullanıcı dostu taşınabilir uygulaması ile Casibom, kumarhane sevenler için ideal bir platform sunuyor.

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注