如果我有一个长度为10 in c的整数数组arr,为了查找arr[5],程序可以简单地将20添加到当前指针位置并检索我的值(常数时间)。
但是如果数组是松散类型的(python/javascript列表),指针如何在恒定时间内知道元素在哪里?因为它不再假设每个元素都是固定字节。

最佳答案

您可以检查python的源代码-listobject.h

typedef struct {
    PyObject_VAR_HEAD
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     * list.sort() temporarily sets allocated to -1 to detect mutations.
     *
     * Items must normally not be NULL, except during construction when
     * the list is not yet visible outside the function that builds it.
     */
    Py_ssize_t allocated;
} PyListObject;

我们可以看到python的list只是指向PyObject的指针数组。所以要访问第五个元素,我们只需要取ob_item[5],它只需在指针ob_item的值上加20(40)。
您可以在listobject.c中看到实际代码:
static PyObject *
list_item(PyListObject *a, Py_ssize_t i)
{
    ...
    Py_INCREF(a->ob_item[i]);
    return a->ob_item[i];
}

07-25 23:54
查看更多