loconsa.blogg.se

Delphi inherit from com interface
Delphi inherit from com interface













The limitation is that intf.GetSelf will fail if intf is nil (while “ as” would just return a nil), though IME, when you’re casting back to the implementation, you’re likely to have filtered against nil far earlier in the code.Īnother option would be Arnaud Bouchez’s ObjectFromInterface, which is constant-time and faster than “as”, but slightly slower than using an IGetSelf (about 7%), and you would be dealing with internal structures magic. So unlike “ as“, it won’t fail you the more you stress it (I first bumped on the issue in a pathological case for “ as” when multi-threading, where it ended up on top of profiling results for no good reason). With the above code, a similar loop completes in 1.23 ms, constant-time, and doesn’t increase when classes implement many interfaces or if you have many classes implementing the same interface. IGetSelf = interface function GetSelf : TObject Īnd parent your Delphi interfaces to some base interface that provides a GetSelf or similar method, and implement it in a root class (in DWScript f.i., it is introduced by a TInterfacedSelfObject). Potion of Speed-CastingĪ faster way to go at it (about 4 to 6 times faster, even when not under stress), which is incidentally compatible with older Delphi versions, is to use something like type Not visible in the benchmark is also the poor cache efficiency of that scanning, should you be dealing with an interface that is implemented by many different classes. gets slower the more interfaces are implemented by the underlying class.įor instance in this benchmark, the “ as” loop takes 5.9 ms when operating on a class implementing 2 interfaces, and 7.1 ms (20% more) when operating on a class implementing 8 interfaces (benchmark code adapted from this one in the comments by Chris Rolliston) However, if “ as” can be convenient in certain scenarios, it’s alas not implemented very efficiently: the compiler and RTL go through several hoops to perform it (cf. end įoo := intf as TFoo // get back the implementation class Here is an alternative that can help both performance and correctness.

delphi inherit from com interface delphi inherit from com interface

Delphi 2010 added support for the “ as” to cast an interface reference to its implementation class.















Delphi inherit from com interface