Comparison of var, int, and object performance in C,
The var keyword is a keyword launched by. net3.5. It mainly allows the compiler to automatically infer and determine the variable type, similar to the var in javascript.
When using some performance optimization software, during code optimization, I found that no matter what type of variables are defined, all types of variables are changed to var. Is the performance of var higher than that of specific types and objects?
Practice:
Create a console application
1/* Var performance test */2 Stopwatch stw = new Stopwatch (); 3 4 List <int> intlist = new List <int> (); 5 stw. start (); 6 for (int I = 0; I <10000000; I ++) {7 var index = I; // use var to transfer in and out 8 intlist. add (index); 9} 10 stw. stop (); 11 Console. writeLine ("Var: {0}", stw. elapsed. ticks); 12 13 14/* Int performance test */15 16 17 List <int> intlist2 = new List <int> (); 18 stw. start (); // Start time 19 for (int I = 0; I <1000000; I ++) {20 int index = I; // use int to transfer in and out 21 intlist2.Add (index); 22} 23 stw. stop (); 24 Console. writeLine ("int: {0}", stw. elapsed. ticks); 25 26/* Object performance test */27 stw. start (); // Start time 28 29 List <int> intlist3 = new List <int> (); 30 for (int I = 0; I <1000000; I ++) {31 object index = I; // use the object to transfer in and out 32 intlist3.Add (int) index); 33} 34 stw. stop (); 35 Console. writeLine ("obj: {0}", stw. elapsed. ticks); 36 37 Console. read ();View Code
Test results:
Summary:
Var performance> int> object
The object type involves packing and unpacking, which is naturally the slowest efficiency.
However, from the test results, the performance of the var type is always better than that of the int or other types.