代码的性能差异

看下面两段代码
        public void A()
        {
            
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()函数比B()多了个(sa.Length > 0)的判断,那么当sa的长度为0时,A()函数和B()函数哪个性能更好、速度更快呢??

再看下面又有两个函数:
        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);
                }
            }
        }
C()和D(),又哪个更快呢??

经过测试,A()和B()基本上没有差别。而C()和D()却不一样,当sa.Count = 0时,C()要比D()快,这是因为D()函数即使在sa.Count = 0时,也要执行获取sa的Enumerator的代码。

那么,再比较一下,C()、D()和下面那个函数:
        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);
                }
            }
        }
有趣的是: E()比C()快,而F()却比D()慢;怎么会这样呢???
这正是泛型的特点,ArrayList构造时要比List<string>的构造快;而到实际取数据的时候List<string>就比ArrayList快了,就才体现泛型的优势嘛?!


原文地址:https://www.cnblogs.com/zhongzf/p/837727.html