Optimizing ARC - weakness of [weak]

In Delphi, the [weak] attribute is used to break strong reference cycles between reference counted object instances. It can be used with the ARC compiler on both object and interface references, and with the classic compiler for interface references. Weak interface references were introduced in Delphi 10.1 Berlin.

Now, there is a teeny-weeny problem with the [weak] attribute. It denotes a zeroing weak reference that will be zeroed (niled) when the object it points to is no longer valid. In order to do that, the compiler has to track such objects at runtime and that introduces some overhead. If you are tracking many such references, that can introduce a significant performance loss.

Not all weak references that serve the purpose of breaking reference cycles need to be zeroed out. If you can guarantee that a [weak] reference will never outlive the object it points to, all that tracking and zeroing is useless. To avoid a performance penalty in such cases, you can use the [unsafe] attribute or a plain pointer.

While figuring out whether you can use [unsafe] instead of [weak] in ARC code is not always straightforward, there are some cases where you can be sure [unsafe] will work perfectly.
Since the classic compiler does not support the [weak] attribute for object references, any cross-platform code that needs to break strong reference cycles on the ARC side can safely use the [unsafe] attribute instead. Plain and simple.

Unfortunately, Delphi frameworks sometimes use [weak] attribute in places (cross-platform code) where they could use [unsafe], making such code less performant.

I have filed a general QP report for that issue https://quality.embarcadero.com/browse/RSP-20087

However, more specific bug reports that point to particular code that is experiencing a performance loss due to usage of the [weak] attribute might be resolved sooner. So if you know about such code, please file additional reports.

Comments

Popular posts from this blog

Delphi 12.1 & New Quality Portal Released

Coming in Delphi 12: Disabled Floating-Point Exceptions

Assigning result to a function from asynchronous code