In the previous question, Inheriting operator overloading , suggested what should be done so that the ancestor could return instances of the heir class.
class Tree<TChild> where TChild : Tree<TChild>, new() { public decimal Mass { get; set; } public static TChild operator +(Tree<TChild> tree1, Tree<TChild> tree2) { var result = new TChild(); result.Mass = tree1.Mass + tree2.Mass; return result; } } class Apple : Tree<Apple> { } static void Main(string[] args) { Apple apple1 = new Apple { Mass = 20 }; Apple apple2 = new Apple { Mass = 30 }; Apple apple3 = apple1 + apple2; // можно присвоить результат сложения в переменную типа Apple }
But it was noted that new TChild()
is a performance bottleneck. Why? What are the options for optimal performance when generating in the ancestor code instances of the heir?