代码的性能差异

看下面两段代码
         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快了,就才体现泛型的优势嘛?!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值