Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do generics in Delphi cause performance bottlenecks?

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;
like image 627
Rahul W Avatar asked Feb 12 '13 07:02

Rahul W


1 Answers

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.

like image 198
Cosmin Prund Avatar answered Oct 11 '22 15:10

Cosmin Prund