Comparison of var, int, and object performance in C,

Source: Internet
Author: User

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.

Related Article

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.