C # syntax for declaring variables (three types ):
Type variable name (strong type declaration)
Var variable name (type to be determined during compilation)
Dynamic variable name (the type is determined when the variable is to be executed)
Which of the following statements is highly efficient?
You can copy the code and execute the following command:
[Csharp]
Using System;
Using System. Diagnostics;
Namespace Var_Test
{
Class Program
{
Static void Main (string [] args)
{
Console. WriteLine ("This program aims to test the execution efficiency of a strong var (inferred type) dynamic (dynamic type ");
Console. WriteLine ("\ t test method :");
Console. WriteLine ("\ t declare variables of the reference type for 1000000 times, and time, and finally output the time. ");
Console. WriteLine ("---- \ t test \ tvar (inferred type) \ t ----");
Stopwatch sw_2 = new Stopwatch ();
Sw_2.Start ();
For (int I = 0; I <1000000; I ++)
{
Var p = new People ();
P. Name = I. ToString ();
P. Age = I;
}
Sw_2.Stop ();
Console. WriteLine ("---- \ t time \ t {0}", sw_2.ElapsedMilliseconds );
Console. WriteLine ("---- \ t test \ t strong type \ t ----");
Stopwatch sw_1 = new Stopwatch ();
Sw_1.Start ();
For (int I = 0; I <1000000; I ++)
{
People p = new People ();
P. Name = I. ToString ();
P. Age = I;
}
Sw_1.Stop ();
Console. WriteLine ("---- \ t time \ t {0}", sw_1.ElapsedMilliseconds );
Console. WriteLine ("---- \ t test \ tdynamic (dynamic type) \ t ----");
Stopwatch sw_3 = new Stopwatch ();
Sw_3.Start ();
For (int I = 0; I <1000000; I ++)
{
Dynamic p = new People ();
P. Name = I. ToString ();
P. Age = I;
}
Sw_3.Stop ();
Console. WriteLine ("---- \ t time \ t {0}", sw_3.ElapsedMilliseconds );
Console. writeLine ("test result: the strong type declaration and Var Declaration are basically the same (Var is slightly slower than the strong type). The reason is that var determines the type during program compilation, and the strong type determines the type during declaration. The. net application is compiled only when it is executed for the first time. ");
Console. WriteLine ("\ t declares variables through dynamic, which is time consuming. ");
Console. WriteLine ("test ended. Press any key to exit. ");
Console. ReadKey ();
}
}
Class People
{
Public string Name {get; set ;}
Public int Age {get; set ;}
}
}
Author: ymchinabye