zoukankan      html  css  js  c++  java
  • static 和 new对象的区别

    static : 无需创建实例可直接使用, 会直到程序关闭才会释放资源

    new 对象: 每次使用时new一次对象,对象使用完会自动释放资源, 下一次再使用时需要从新new一次 

    测试性能对比:

    static void Main(string[] args)
            {
                var count = 1000000000; 
                //test static class
                var start2 = DateTime.Now;
                for (int i = 0; i < count; i++)
                {
                    Test.StaticSum();
                }
                var end2 = DateTime.Now;
                Console.WriteLine($"normal: {end2.Subtract(start2)}");
    
                //test class
                var start1 = DateTime.Now;
                for (int i = 0; i < count; i++)
                {
                    var t1 = new Test();
                    t1.Sum();
                }
                var end1 = DateTime.Now;
                Console.WriteLine($"normal: {end1.Subtract(start1)}");
    
                Console.ReadLine();
            }

    结果如下:

    结论:

    在频繁需要使用的对象, 建议使用static

    注意: 内存是有限的, 好比一个容器, static每用一次就在往容器加一点, 如果滥用static, 可能会造成内存泄漏

  • 相关阅读:
    C++中的类模板详细讲述
    函数模板和模板函数
    vs2008 快捷键大全
    #宏定义##
    多工程项目设置
    conemu 配置
    itcast-svn
    itcast-spring-三大框架整合
    Spring通知方法错误
    动态代理
  • 原文地址:https://www.cnblogs.com/zxhome/p/11362097.html
Copyright © 2011-2022 走看看