Three ways to instantiate the performance of a class

Source: Internet
Author: User

SOURCE content: http://www.cnblogs.com/shouce/p/5558095.html#undefined

The following content is based on the "source content" has been rectified, supplemented.

three ways to instantiate a class, including the parameter-free construction form and the performance test of parametric construction .

    1. Use the new keyword to create a class instance (common way).
    2. Use the Activator Activator class to create the class instance (Activator to create the object type locally or remotely, or to get a reference to an existing remote object).
    3. Create a class instance using the Assembly assembly (Assembly represents an assembly, which is a reusable, version-free, and self-describing common language runtime application building block. The class can load an assembly, browse the Assembly's metadata and constituent parts, discover the types contained in the assembly, and create instances of those types.

Test environment:

1) Visual Studio Community

2) Windows Ten Profession

3) Memory 6g,cpu inter-core-i3-3220 @ 3.3GHz

The test code is as follows: interface, interface implementation class, instantiation class creation, execution test method, respectively.

/// <summary>///occupation, Industry/// </summary> Public Interfaceiprofession{stringName {Get; } stringmostmeaningthing ();}/// <summary>///workers, blue-collar/// </summary> Public classworker:iprofession{ PublicWorker (stringname) {Name=name; }     PublicWorker () {} Public stringName {Get;Private Set; }  Public stringmostmeaningthing () {return "excavator which strong Shandong find Lanxiang"; }}  Public classinstanceclass{//can be modified according to the name of your project    Private stringClassName ="Testproblem.worker"; //Number of executions    Private intTime =100000; /// <summary>    ///whether to execute a parametric constructor/// </summary>    Private BOOLhasparameters;  PublicInstanceclass (BOOLhasparameters) {         This. Hasparameters =hasparameters; }    /// <summary>    ///created with the new keyword/// </summary>     Public voidcreatebynew () {iprofession profession; Stopwatch Watch=NewStopwatch (); Watch.        Start ();  for(inti =0; I < time; i++) {Profession= Hasparameters?NewWorker ("worker-new-"+ i):NewWorker (); } watch.        Stop (); Console.Write (watch. Elapsedmilliseconds.tostring (). PadLeft (5)); }    /// <summary>    ///Create with Activator control class/// </summary>     Public voidCreatebyactivator () {Type type=Type.GetType (className);        Iprofession profession; Stopwatch Watch=NewStopwatch (); Watch.        Start ();  for(inti =0; I < time; i++)        {            Objectobj = hasparameters? Activator.CreateInstance (Type,"worker-activator-"+i): Activator.CreateInstance (type); Profession= obj asiprofession; } watch.        Stop (); Console.Write (watch. Elapsedmilliseconds.tostring (). PadLeft (5)); }    /// <summary>    ///Create with Assembly control class/// </summary>     Public voidcreatebyassembly () {Assembly Assembly=assembly.getassembly (Type.GetType (className));        Iprofession profession; Stopwatch Watch=NewStopwatch (); Watch.        Start ();  for(inti =0; I < time; i++)        {            Objectobj = hasparameters?Assembly. CreateInstance (ClassName,true, Bindingflags.default,NULL,New Object[] {"worker-assembly-"+ i}, CultureInfo.CurrentCulture,NULL): assembly.            CreateInstance (ClassName); Profession= obj asiprofession; } watch.        Stop (); Console.Write (watch. Elapsedmilliseconds.tostring (). PadLeft (5)); }    /// <summary>    ///For Loop , in place of multiple handwriting similar for loop code in code/// </summary>    /// <param name= "Time" >Number of Cycles</param>    /// <param name= "Action" >Delegate</param>     Public Static voidForloop (intTime, action<int>action) {         for(inti =0; I < time; i++) {action (i); }    }    /// <summary>    ///for loop, encapsulating for loop code execution/// </summary>    /// <param name= "Time" >Number of Cycles</param>    /// <param name= "Action" >delegate, function pointer</param>     Public Static voidForloop (intTime , Action action) {         for(inti =0; I < time; i++) {action (); }    }}/// <summary>///100,000 instances of creating classes executed 10 times/// </summary>Private Static voidExecutelakh () {BOOLHasparameters =true; Console.WriteLine ("Performance comparison of instantiating a class ({0} parameter construct) (in milliseconds)", Hasparameters?"have a":"No"); Console.Write ("\t\t\t"); Instanceclass.forloop (Ten, I = Console.Write ("{0:g}", (i +1). ToString (). PadLeft (5)));    Console.WriteLine (); Instanceclass Instanceclass=NewInstanceclass (hasparameters); Console.Write ("createbynew". PadRight ( -)); Instanceclass.forloop (Ten, () =instanceclass.createbynew ());    Console.WriteLine (); Console.Write ("Createbyactivator". PadRight ( -)); Instanceclass.forloop (Ten, () =instanceclass.createbyactivator ());    Console.WriteLine (); Console.Write ("createbyassembly". PadRight ( -)); Instanceclass.forloop (Ten, () =instanceclass.createbyassembly ()); Console.WriteLine ();}

The test results are as follows:

Three ways to instantiate the performance of a class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.