首页 > 其他 > 详细

颠覆三观的性能实验

时间:2021-01-04 14:40:23      阅读:18      评论:0      收藏:0      [点我收藏+]

用抽象接口来接收实现是我们代码中常用的一种手段 IBase base = new Child() ,从来没想过在.net Framework下会对性能造成如此影响。

具体代码如下

private static void Test()
        {
           Base a = new Base();
            AbsBase b = a;
            Child c = new Child();
            IBase d = c;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < length; i++)
            {
                a.Do();
            }
            Console.WriteLine($"抽象实现类:{stopwatch.ElapsedMilliseconds}");
            stopwatch.Restart();
            for (int i = 0; i < length; i++)
            {
                b.Do();
            }
            Console.WriteLine($"抽象基类:{stopwatch.ElapsedMilliseconds}");
            stopwatch.Restart();
            for (int i = 0; i < length; i++)
            {
                c.Do();
            }
            Console.WriteLine($"接口实现类:{stopwatch.ElapsedMilliseconds}");
            stopwatch.Restart();
            for (int i = 0; i < length; i++)
            {
                d.Do();
            }
       stopwatch.Stop();
       Console.WriteLine($"接口:{stopwatch.ElapsedMilliseconds}");
}

 

技术分享图片
    public abstract class AbsBase
    {
        public abstract void Do();
    }

    public class Base : AbsBase
    {
        public override void Do()
        {

        }
    }

    public interface IBase
    {
        public void Do();
    }

    public class Child : IBase
    {
        public void Do()
        {
        }
    }
辅助类定义

Core下运行效果:

技术分享图片

 

 Framework下运行效果

技术分享图片

 

 二者效果相差甚远

颠覆三观的性能实验

原文:https://www.cnblogs.com/sunpan/p/14229145.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!