What is the data structure behind NSMutableArray?

后端 未结 2 2016
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 10:19

Usually, a \"mutable array\" class is implemented as a wrapper around a simple array. The wrapper allocates more memory when you add an element past the end. This is a commo

2条回答
  •  心在旅途
    2020-12-13 11:04

    Did some measurements: Starting with an empty array, added @"Hello" 100,000 times, then removed it 100,000 times. Different patterns: Adding/removing at the end, at the start, in the middle, close to the start (at index 20 when possible), close to the end (20 indexes away from the end when possible), and one where I alternated between close to the start and the end. Here's the times for 100,000 objects (measured on Core 2 Duo):

    Adding objects = 0.006593 seconds
    Removing objects at the end = 0.004674 seconds
    Adding objects at the start = 0.003577 seconds
    Removing objects at the start = 0.002936 seconds
    Adding objects in the middle = 3.057944 seconds
    Removing objects in the middle = 3.059942 seconds
    Adding objects close to the start = 0.010035 seconds
    Removing objects close to the start = 0.007599 seconds
    Adding objects close to the end = 0.008005 seconds
    Removing objects close to the end = 0.008735 seconds
    Adding objects close to the start / end = 0.008795 seconds
    Removing objects close to the start / end = 0.008853 seconds
    

    So the time for each add / remove is proportional the distance to the beginning or end of the array, whichever is closer. Adding things in the middle is expensive. You don't have to work exactly at the end; removing elements close to the start / end is also quite cheap.

    The suggested implementation as a circular list omits an important detail: There is a gap of variable size between the location of the last and the first array element. As array elements are added / removed, the size of that gap changes. More memory needs to be allocated and object pointers need to be moved when the gap disappears and more objects are added; the array can be shrunk and object pointers need to be moved when the gap becomes too large. A simple change (allowing the gap to be located at any location, not just between last and first element) would allow changes at any location to be fast (as long as it is the same location), and would make operations that "thin out" the array faster.

提交回复
热议问题