- Mastering Cross:Platform Development with Xamarin
- Can Bilgin
- 361字
- 2021-07-09 20:05:18
Platform-specific concepts
In order to understand the memory management techniques and pitfalls, one must understand some platform-related concepts. Even though Xamarin provides an almost platform agnostic development experience, iOS and Android platforms deal with memory allocations and references slightly differently from .NET CLR and each other.
Object reference types
Referred objects can be classified according to application needs. This classification helps the garbage collector decide whether the memory allocation can be released for the referred objects.
A strong reference protects the object from being "garbage collected". A referred object is said to be strongly referenced/reachable when the class instance is directly used by the current execution context.
Weak references can be used for class instances when the need for the reference does not interfere with garbage collection. When the referred object is weakly reachable, the dependent section of code has to check whether the object is still alive before using the referenced object. Weak references have two types in CLR according to the dispose and finalization processes implemented by the declaring types: long and short weak references. Long weak references are types that can live on to be recreated and can be finalized by a destructor rather than being disposed or garbage collected.
Soft and phantom references are specific to Android runtime. Soft references, in simple terms, are a little more persistent than the weak references, and would only be cleared up by the garbage collector under memory pressure even though the object is no longer strongly reachable. Phantom references are the weakest reference in Android runtime. They are only used to implement specialized object finalization methods and have to be associated with a reference queue for processing.
Automatic Reference Counting (ARC)
Automatic Reference Counting is a compiler feature that was introduced in iOS 5. It is referred to as a compiler feature since it cannot be classified as a garbage collection implementation. It is a static analysis implementation where the compiler analyses the code execution tree and inserts retain and release messages according to the object persistence requirements.
With ARC, traditional memory management calls are not allowed to be inserted in the application to allocate memory and release memory addresses.