问题
Recently i have been developing an application and wanted to have a collections of several types. I don't want to declare and implement a new collection class for it's type. So, i thought of going with generics, but wasn't sure about the performance of Generics compared to normal typed instances. Performance is the major thing that i am looking at. My application is time critical and even loosing few 100 milliseconds is also not advisable.
I am using Delphi XE3
For eg:
ICollectionItem = interface
function GetID : string;
property ID : string read GetId;
end;
TGenericCollection<T: ICollectionItem> = class
function Add(T) : Integer;
end;
compared to
TSomeClass = class(TInterfacedObject, ICollectionItem)
function GetId : string;
end;
TSomeClassList = class
function Add(item : TSomeClass) : Integer;
end;
回答1:
No performance bottleneck
Delphi generics are compiled. The compiler knows the concrete types at compile time and it's going to do it's best to provide you with the best code it can. There should be no differences between generic and non-generic code when inspecting the generated code at run time.
There's a good chance to get better code with generics, because you're more likely to use ready-made, efficient, type-safe data structures. When rolling your own you're likely to cut corners because lets be honest, writing sorting algorithms, efficient allocation, etc is hard.
来源:https://stackoverflow.com/questions/14827475/do-generics-in-delphi-cause-performance-bottlenecks