What are the pros and cons of using interfaces in Delphi?

前端 未结 9 1565
既然无缘
既然无缘 2021-01-31 17:21

I have used Delphi classes for a while now but never really got into using interfaces. I already have read a bit about them but want to learn more.

I would like to hear

9条回答
  •  别那么骄傲
    2021-01-31 18:00

    Extra note on Cons: Performance

    I think many people are too blithely dismissing the performance penalty of interfaces. (Not that I don't like and use interfaces but you should be aware of what you are getting into). Interfaces can be expensive not just for the _AddRef / _Release hit (even if you are just returning -1) but also that properties are REQUIRED to have a Get method. In my experience, most properties in a class have direct access for the read accessor (e.g., propery Prop1: Integer read FProp1 write SetProp1). Changing that direct, no penalty access to a function call can be significant hit on your speed (especially when you start adding 10s of property calls inside a loop.

    For example, a simple loop using a class

    for i := 0 to 99 do
    begin
      j := (MyClass.Prop1 + MyClass.Prop2 + MyClass.Prop3) / MyClass.Prop4;
      MyClass.Update;
      // do something with j
    end;
    

    goes from 0 function calls to 400 function calls when the class becomes an interface. Add more properties in that loop and it quickly gets worse.

    The _AddRef / _Release penalty you can ameliorate with some tips (I am sure there are other tips. This is off the top of my head):

    • Use WITH or assign to a temp variable to only incur the penalty of one _AddRef / _Release per code block
    • Always pass interfaces using const keyword into a function (otherwise, you get an extra _AddRef / _Release occurs every time that function is called.

提交回复
热议问题