Manual Memory Management vs. ARC for Cross-Platform Object Lifecycles
0 reputation · 16 Jan 2023, 17:52 UTC
0 reputation · 16 Jan 2023, 17:52 UTC
When developing cross-platform applications in RAD Studio for both desktop (Windows/macOS) and mobile (iOS/Android) targets, developers must navigate differing memory management models. Desktop targets rely on manual memory management, necessitating explicit Free or Dispose calls, typically wrapped in try..finally blocks to prevent leaks.
Mobile platforms historically utilize Automatic Reference Counting (ARC) to automate object lifecycles. While ARC reduces the risk of leaks, it introduces the possibility of retain cycles and non-deterministic destruction, often requiring the implementation of weak references to break circular dependencies.
The challenge arises when maintaining a shared codebase where the same object logic must operate under both models without introducing platform-specific memory corruption or leaks.
Which approach is more sustainable for long-term maintenance: implementing a unified wrapper that mimics ARC behavior on desktop, or utilizing strict conditional compilation to separate manual and automatic lifecycle management? What are the performance implications of simulating reference counting on desktop targets?
35275 reputation · 16 Jan 2023, 21:53 UTC
For long‑term maintainability, a single ARC‑style reference‑counting wrapper on desktop is the more sustainable choice. It keeps the shared codebase free of platform‑specific Free/Dispose logic, reduces the risk of mismatched cleanup, and aligns the desktop lifecycle model with the mobile ARC model. The trade‑off is a modest runtime overhead that must be measured against the application’s allocation profile.
Retain and Release, so the same code compiles for Windows, macOS, iOS, and Android.Release calls in try..finally blocks, preserving deterministic destruction while avoiding manual Free calls.{$IFDEF} branches.TRefCounted base class that implements Retain and Release using AtomicIncrement/AtomicDecrement.TRefCounted and replace every Free with Release inside try..finally.Weak references to break cycles.Free path for that module while the rest of the code uses the wrapper.Free calls in the shared code when the wrapper is enabled.To decide whether the wrapper overhead is acceptable, I need the typical allocation frequency for desktop targets (objects per second). Please provide that figure so the benchmark can be tailored to your workload.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.