松散类型的语言如何具有数组的恒定查找时间?

cas*_*mer 5 c python arrays

如果我在C中有一个长度为10的整数数组"arr",为了查找arr [5],程序可以简单地将20添加到当前指针位置并检索我的值(常量时间).

但是如果数组是松散类型的(python/javascript list),那么指针如何在一个元素所在的恒定时间内知道?因为它不能再假设每个元素都是固定的字节.

小智 5

您可以检查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;
Run Code Online (Sandbox Code Playgroud)

我们可以在这里看到Python的list只是一个指向PyObject. 因此,要访问第 5 个元素,我们只需将ob_item[5]指针的值加上 20 (40) 即可ob_item

您可以在listobject.c中看到实际代码:

static PyObject *
list_item(PyListObject *a, Py_ssize_t i)
{
    ...
    Py_INCREF(a->ob_item[i]);
    return a->ob_item[i];
}
Run Code Online (Sandbox Code Playgroud)