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快了,就才体现泛型的优势嘛?!


  • 相关阅读:
    自学入门 Python 优质中文资源索引
    Crawlab Lite 正式发布,更轻量的爬虫管理平台
    一款被大厂选用的 Hexo 博客主题
    源码解读 Golang 的 sync.Map 实现原理
    探究 Go 语言 defer 语句的三种机制
    一道快速考察 Python 基础的面试题
    编写自己的 GitHub Action,体验自动化部署
    Python 2 与 3 共存了 11 年,新年就要和它道别
    30 年前的圣诞节,Python 序章被谱写
    文言文编程火了,可我完全学不懂
  • 原文地址:https://www.cnblogs.com/zhongzf/p/837727.html
Copyright © 2011-2022 走看看