Code performance differences

Source: Internet
Author: User
See the following two sections of code: Public void ()
{
String [] sa = new string [0];
If (sa! = Null) & (sa. Length> 0 ))
{
Foreach (string s in sa)
{
System. Console. WriteLine (s );
}
}
}

Public void B ()
{
String [] sa = new string [0];
If (sa! = Null)
{
Foreach (string s in sa)
{
System. Console. WriteLine (s );
}
}
}

A () function has more than B () (sa. when the sa Length is 0, which of the () and B () functions has better performance and faster speed ??

Let's look at two more functions: Public void C ()
{
List <string> sa = new List <string> ();
If (sa! = Null) & (sa. Count> 0 ))
{
Foreach (string s in sa)
{
System. Console. WriteLine (s );
}
}
}

Public void D ()
{
List <string> sa = new List <string> ();
If (sa! = Null)
{
Foreach (string s in sa)
{
System. Console. WriteLine (s );
}
}
}

Which of the following is faster ??

After testing, there is basically no difference between A () and B. C () and D () are different. when Count = 0, C () is faster than D (), because the D () function is even in sa. when Count = 0, you must also execute the code to obtain the sa's Enumerator.

Then, compare C (), D (), and the following function: Public void E ()
{
System. Collections. ArrayList sa = new System. Collections. ArrayList ();
If (sa! = Null) & (sa. Count> 0 ))
{
Foreach (string s in sa)
{
System. Console. WriteLine (s );
}
}
}

Public void F ()
{
System. Collections. ArrayList sa = new System. Collections. ArrayList ();
If (sa! = Null)
{
Foreach (string s in sa)
{
System. Console. WriteLine (s );
}
}
}

Interestingly, E () is faster than C (), while F () is slower than D (). How can this happen ???
This is a wildcard feature. ArrayList construction is faster than List <string> construction, while List <string> is faster than ArrayList in actual data retrieval, can this reflect the advantages of generics ?!

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.