当前位置:网站首页>C # generics and performance comparison

C # generics and performance comparison

2022-07-08 00:22:00 A descendant of the sun

What is generics ? Generally speaking, it is the type of uncertainty .

When to use generics ? When we want to use a method to receive many different types of parameters, we can often use .

public static void Show()
{
    
    Console.WriteLine("****************Monitor******************");
    {
    
        int iValue = 12345;
        long commonSecond = 0;  
        long objectSecond = 0;
        long genericSecond = 0;

        {
    
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < 100_000_000; i++)
            {
    
                ShowInt(iValue);
            }
            watch.Stop();
            commonSecond = watch.ElapsedMilliseconds;
        }
        {
    
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < 100_000_000; i++)
            {
    
                ShowObject(iValue);
            }
            watch.Stop();
            objectSecond = watch.ElapsedMilliseconds;
        }
        {
    
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < 100_000_000; i++)
            {
    
                Show<int>(iValue);
            }
            watch.Stop();
            genericSecond = watch.ElapsedMilliseconds;
        }
        Console.WriteLine("commonSecond={0},objectSecond={1},genericSecond={2}"
            , commonSecond, objectSecond, genericSecond);
    }
}

#region PrivateMethod
private static void ShowInt(int iParameter)
{
    
    //do nothing
}
private static void ShowObject(object oParameter)
{
    
    //do nothing
}
private static void Show<T>(T tParameter)
{
    
    //do nothing
}
#endregion

result
 Insert picture description here
In other words, the performance of ordinary methods is greater than that of generic methods of specified types, and greater than that of generic methods of unspecified types

Sometimes I really envy , Envy some people can never forget , We can draw inferences from one example , And I often have to read the same information many times to really understand .

But fortunately , Many things can be changed and obtained by hard work , Knock more code , Your skills will gradually improve , Run more , Your figure will get better , Listen to books more , I can also be full of experience .

come on. , Over the weekend , You should be better and better , This need not be seen by others , But you must know .

原网站

版权声明
本文为[A descendant of the sun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/189/202207072217072715.html