What is the difference between Objective-C automatic reference counting and garbage collection?

后端 未结 4 601
[愿得一人]
[愿得一人] 2020-11-27 11:44

With the new automatic reference counting (ARC) introduced in Xcode 4.2, we no longer need to manually manage retain / release in Objective-C.

This seems similar to

4条回答
  •  盖世英雄少女心
    2020-11-27 12:16

    ARC rely on a compile time "referenced" objects which make it efficient in a low-power mode environments (Mobile devices).

    GC rely on a runtime based "reachable" objects which make it efficient in a multi-threaded environment.

    Operation

    ARC injects a code into the executable to be executed "automatically" on unused objects depending on their reference count.

    GC works in the runtime as it will detect the unused object graphs (will eliminate retain-cycles) and remove them on an indeterminate time intervals

    Advantages of Automatic Reference Counting

    • Real-time, deterministic destruction of objects as they become unused.
    • No background processing.

    Advantages of Garbage Collection

    • GC can clean up entire object graphs, including retain cycles.
    • GC proceed in the background, so less memory management work is done as part of the regular application flow.

    Disadvantages of Automatic Reference Counting

    • ARC cannot handle retain cycles automatically.

    Disadvantages of Garbage Collection

    • Because GC happens in the background, the exact time frame for object releases is undetermined.
    • When a GC happens, other threads in the application may be temporarily put on hold.

提交回复
热议问题