views:

213

answers:

3

If I replace all object references in my Delphi program with interface references, and use objects which are inherited from TInterfacedObject, will the resulting application run with the same speed as before? Or does the reference counting add a significant execution overhead at run time?

+6  A: 

Interfaced classes do carry an overhead of incrementing and releasing the reference count of each instance you create, pass and destroy, but unless you are creating, destroying and passing references in tight loops, you shouldn't experience any significant slow down.

You can of course disable reference counting as such by returning -1 in the _AddRef and _Release overrides, but that doesn't prevent the compiler from generating those calls...

Marjan Venema
+1  A: 

Not only reference counting - just calling object's methods via interface reference always implies overhead. Here you can read how object's methods are called via interface reference in Delphi.

Serg
+7  A: 

The reference counting can affect you if you do a lot of assignments of those interfaces (or pass them as non-const, non-var parameters in function calls).

However the real trouble often isn't the reference counting itself, but the implicit try-finally constructs the compiler adds to protect the reference counting, which will add up to your calls overhead, and can be most painful if you have many simple methods (vs a single big procedure with all your code inside, which you don't really want).

To mitigate that aspect, always pass interfaces as either const or var parameters, avoid returning interfaces as function call result, and minimize usage of local variables of interface type, prefer const parameters and direct object field usages.

Eric Grange
So (besides use in interfaces) a `try finally` block would also have a significant effect on speed, even if no exceptions occur?
mjustin
Yes it can, especially in simple procedures, because a try-finally represents quite a bit of code (at the asm level), and it also prevents the compiler from generating the most efficient entry and exit code.For instance check this, it's a case of an implicit try-finally protecting code that isn't even executed, because implicit try-finally are attached to the compiler to procedure they're in, and not to the code that can fail. So you pay for it in procedure calls, even if you don't execute the code that can fail.http://delphitools.info/2009/05/06/code-optimization-go-for-the-jugular/
Eric Grange