zoukankan      html  css  js  c++  java
  • 代码的性能差异

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


  • 相关阅读:
    Volatile关键字
    ThreadPoolExecutor线程池基本原理及使用
    HashMap线程不安全源码解析(1.7 + 1.8)
    SpringBoot+ajax+formData实现图片上传和回显
    BloomFilter
    POST和GET
    快手电话面试
    Apache SSI 远程命令执行漏洞
    SYSTEM--服务器提权
    封神台靶场练习(2)
  • 原文地址:https://www.cnblogs.com/zhongzf/p/837727.html
Copyright © 2011-2022 走看看