[fpc-devel] Suggestion: reference counted objects

Sven Barth pascaldragon at googlemail.com
Sun Sep 21 16:25:23 CEST 2014


On 21.09.2014 15:09, Marco van de Voort wrote:
> In our previous episode, Sven Barth said:
>> No, not multiple roots. If a class is declared as refcounted (and it's
>> parent class is not) then a hidden field is inserted into its list of
>> fields, just as a normal one would, only that it isn't accesible using
>> the "."-operator (because it won't have a valid Pascal identifier). The
>> compiler of course knows the offset at compile time and at runtime the
>> field can be accessed using the class' RTTI which would have a
>> "RefCountOffset" field added (if that offset is < 0 then the object does
>> not support reference counting).
>
> So in summary: the compiler must pass the fieldoffset to the runtime helper,
> instead of having one refcounted root with known offset.

Yes. That avoids having a single rooted refcounted object and thus 
allowing the usage of "refcounted" further down the inheritance tree.

Considering that the helper would only consist of a 
"InterlockedIncrement(AddressOfRefCount)" or 
"InterlocedDecrement(AddressOfRecCount)" one could optimize this by 
declaring the helper compilerproc as "inline", thus avoiding one call.

>> Did anyone till now really complain about the performance impact of
>> reference counting on interfaces? Especially since they are used *so*
>> much in today's OOP designs?
>
> I never really benchmarked it. I never use interfaces in my own abstract
> data structure designs, mostly because the existing classes don't, and I
> don't like the refcount. (since i usually also need to access the classes as
> normal instances)
>
> I did benchmark interfaces in combination with variants as part of a decal
> evaluation.  That was, euh, painful.

I can imagine that benchmarking variants was painful. ;)
But considering that interfaces are so "en vogue" today in Delphi 
communities the performance hit might not be that killer criteria...

>>
>> function Test: TObject;
>> begin
>>     Result := (TTestClass.Create as IInterface) as TTestClass;
>> end;
>
> Hmm. This looks like a (Delphi) faq item to me, how to convert interface back to a
> class. Usually the answer is IComponentreference (or what it is called), if
> this is legal, I wonder why it didn't come up before.

The intf-to-class-as-operator was added with Delphi 2007 AFAIK and FPC 
supports it as well in 2.6.0. If you want specifics, then look at the 
helper functions fpc_intf_is_class (for the is operator) and 
fpc_intf_cast_class (for the as operator) in $fpcdir/rtl/inc/objpas.inc.

Regards,
Sven



More information about the fpc-devel mailing list