如果在C中有一个长度为10的整数数组"arr“,要查找arr5,程序可以简单地将20添加到当前指针位置并检索我的值(恒定时间)。
但是,如果数组是松散类型的(python/javascript列表),那么指针如何知道元素在固定时间内的位置?因为它不能再假设每个元素都是固定的字节。
发布于 2018-02-11 03:12:45
您可以检查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的一系列指针。因此,要访问第5个元素,我们只需使用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];
}https://stackoverflow.com/questions/48717082
复制相似问题