• 使用struct与使用class初始化对象效率对比


    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApp4
    {
        public struct A1 {
            public int a { get; set; }
            public int b { get; set; }
            public int c { get; set; }
            public int d { get; set; }
    
    
        }
    
        public class B1
        {
            public int a { get; set; }
            public int b { get; set; }
            public int c { get; set; }
            public int d { get; set; }
    
    
        }
        class Program
        {
            static void Main(string[] args)
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                for (int i = 0; i < 10000000; i++)
                {
                    var A = new A1();
                }
                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
                watch = new Stopwatch();
                watch.Start();
                for (int i = 0; i < 10000000; i++)
                {
                    var B = new B1();
                }
                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
                Console.Read();
    
    
            }
        }
    }
    

    执行结果  

    1. struct在栈里面,class在堆里面。

    2. struct不支持继承。

    3. struct 不能有参数为空的构造函数,如果提供了构造函数,必须把所有的变量全都初始化一遍

    4. 不能直接初始化变量。

    5. struct是值类型,class是引用类型,这是最本质区别。

    6. struct轻量级,class重量级。

    7. 当涉及数组操作时,struct效率高,涉及collection操作时,class效率高

  • 相关阅读:
    php读取大文件如日志文件
    大型站点高并发架构技术
    Nginx配置文件nginx.conf详细说明文档
    关于PHP高并发抢购系统设计
    Mysql常用的锁机制
    Sping基础
    Reliable Master持续集成环境搭建Centos
    Win7 macaca自动化环境搭建 PC篇
    安卓appium无线调试
    Selenium PageFactory使用
  • 原文地址:https://www.cnblogs.com/ProDoctor/p/6999716.html
Copyright © 2020-2023  润新知