SoFunction
Updated on 2025-03-07

Examples of performance comparison between C# generics and non-generics


using System;
using ;
using ;
using ;
using ;
namespace ConsoleApplication
{
    class Program
    {
        static int length = 1000 * 1000;
        static void Main(string[] args)
        {
int iteration=10;//Number of method execution
("Value type processing-generic method", iteration, Test1);
("Value type processing-non-generic method", iteration, Test2);
//("Reference type processing-generic method", iteration, Test3);
//("Reference type processing-non-generic method", iteration, Test4);
            ();
        }
        /// <summary>
/// Value type generic method
        /// </summary>
        static  void Test1()
        {
            List<int> l = new List<int>();
            for (int i = 0; i < length; i++)
            {
                (i);
                int a = l[i];
            }
            l = null;
        }
        /// <summary>
///Non-generic method of value type
        /// </summary>
        static void Test2()
        {
            ArrayList a = new ArrayList();
            for (int i = 0; i < length; i++)
            {
                (i);
                int s = (int)a[i];
            }
            a = null;
        }
        /// <summary>
/// Reference type generic method
        /// </summary>
        static void Test3()
        {
            List<string> l = new List<string>();
            for (int i = 0; i < length; i++)
            {
                ("l");
                string s = l[i];
            }
        }
        /// <summary>
/// Non-generic methods of reference types
        /// </summary>
        static void Test4()
        {
            ArrayList a = new ArrayList();
            for(int i=0;i<length;i++)
            {
                ("a");
                string s = (string)a[i];
            }
            a = null;
        }
    }
}