用抽象接口来接收实现是我们代码中常用的一种手段 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